获取jQuery集中最宽的元素

时间:2013-07-07 01:39:58

标签: javascript jquery css

假设我有一堆具有不同文本内容的<span>元素。

我怎样才能获得最宽的<span>

jQuery很好。我只关心识别跨度,而不是宽度本身的值。

类似的问题是here。但他们只得到宽度的值。

以下是我的开始:

$('span').each(function(id, value){
  if ($(this).width() > w) {
    largestSpan = id;
  }
});

2 个答案:

答案 0 :(得分:17)

var maxWidth = 0;
var widestSpan = null;
var $element;
$("span").each(function(){
   $element = $(this);
   if($element.width() > maxWidth){
     maxWidth = $element.width();
     widestSpan = $element; 
   }

});

答案 1 :(得分:5)

使用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.
});