2009-08-05 9 views
2

jQueryを使用してWebページ上で最も幅広いアイテム(CSSまたは属性として設定された幅)を見つける方法はありますか?jQuery - ページの最も広いアイテム

+0

幅が_explicitly_に設定されている最も広いものはありますか? – jason

+0

その幅は?本文文書ウィンドウ画面 –

答えて

8

は文句を言わない高速であるが、このバージョンはわずかに速い(間違いなくそうclienatない)かもしれない

これはトリックを行う必要があり

var widest = null; 
$("*").each(function() { 
    if (widest == null) 
    widest = $(this); 
    else 
    if ($(this).width() > widest.width()) 
    widest = $(this); 
}); 

トリックを行う必要があります。

var widest = null; 
// remember the width of the "widest" element - probably faster than calling .width() 
var widestWidth = 0; 
$("*").each(function() { 
    if (widest == null) 
    { 
    widest = $(this); 
    widestWidth = $(this).width(); 
    } 
    else 
    if ($(this).width() > widestWidth) { 
    widest = $(this); 
    widestWidth = $(this).width(); 
    } 
}); 

Iをまた、通過するノードのタイプを制限することをお勧めします(つまり、*の代わりにdivを使用してください)

+1

必要に応じてouterWidth()をチェックしたい場合があります。 – Martin

+0

DOMの長さに注意してください。この呼び出しはコストがかかる可能性があります。 –

+0

意味がある、私は願って、ある種のmax機能を望んでいたと思う。 – Jeremy

2

Gお返事はNiko!

これは、表示されるページ上の要素のみを表示するように少し構築されています。表示される要素が大きくなることがあります。

var widest = null; 

$("*").each(function() { 
    if (widest === null && $(this).is(':visible')) { 
     widest = $(this); 
    } else if ($(this).is(':visible') && $(this).width() > widest.width()) { 
     widest = $(this); 
    } 
}); 
関連する問題