[英]Get widest element in a jQuery set
假設我有一堆帶有不同文本內容的<span>
元素。
我怎樣才能獲得最寬的<span>
?
jQuery很好。 我只關心識別跨度,而不是寬度本身的值。
類似的問題在這里 。 但他們只得到寬度的值。
這是我開始的方式:
$('span').each(function(id, value){
if ($(this).width() > w) {
largestSpan = id;
}
});
var maxWidth = 0;
var widestSpan = null;
var $element;
$("span").each(function(){
$element = $(this);
if($element.width() > maxWidth){
maxWidth = $element.width();
widestSpan = $element;
}
});
使用jQuery識別div中最寬的范圍:
var oSpan; // Container object for loop item
var oWidest; // Container object for current widest in loop
var nWidth = 0; // Int to store current span width
var nWidest = 0; // Int to contain widest items width
var aWidest = []; // Array to contain multiple matching spans
// Call each function on spans within div
$('#divContainer span').each(function(nIndex)
{
// Set reference to current span to avoid multiple calls per iteration
oSpan = $(this);
// Set current width to avoid multiple calls per iteration
nSpanWidth = oSpan.width();
// Compare current width to widest width
if (nSpanWidth == nWidest)
{
// If exact,add to array and set current widest items
aWidest.push(oSpan);
oWidest = oSpan;
nWidest = nSpanWidth;
}
else if( nSpanWidth >= nWidest )
{
// If wider, reset array and set current widest item
oWidest = oSpan;
nWidest = nSpanWidth;
aWidest = [].push(oWidest)
}
else { } // Move along short stuff.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.