获取jQuery集中最宽的元素

假设我有一堆带有不同文本内容的元素。

我怎样才能获得最宽的

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