最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get widest element in a jQuery set - Stack Overflow

programmeradmin0浏览0评论

Let's say I have a bunch of <span> elements with different text content.

How I can I get the widest <span>?

jQuery is fine. I only care about identifying the span, not the value of the width itself.

A similar question is here. But they only get the value of the width.

Here's how I'd start:

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

Let's say I have a bunch of <span> elements with different text content.

How I can I get the widest <span>?

jQuery is fine. I only care about identifying the span, not the value of the width itself.

A similar question is here. But they only get the value of the width.

Here's how I'd start:

$('span').each(function(id, value){
  if ($(this).width() > w) {
    largestSpan = id;
  }
});
Share Improve this question edited May 23, 2017 at 12:24 CommunityBot 11 silver badge asked Jul 7, 2013 at 1:39 Don PDon P 63.6k121 gold badges318 silver badges447 bronze badges 0
Add a comment  | 

2 Answers 2

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

});

Using jQuery to identify widest span in a 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.
});
发布评论

评论列表(0)

  1. 暂无评论