7

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

我怎样才能得到最广泛的<span>

jQuery 很好。我只关心确定跨度,而不关心宽度本身的值。

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

这是我开始的方式:

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

2 回答 2

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

});
于 2013-07-07T01:45:55.937 回答
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.
});
于 2013-07-07T01:47:11.020 回答