【问题标题】:How to calculate width of list items如何计算列表项的宽度
【发布时间】:2009-10-15 06:16:22
【问题描述】:

我正在尝试计算不同的列表项

我的 HTML:

  <ul>

     <li style="disply:block; float:left">Some Text</li>
     <li style="disply:block; float:left">Some More Text</li>
     <li style="disply:block; float:left">Some Other Text</li>

 </ul>

我在函数中使用标准

var width = $('li').outerWidth()

但这会根据第一个标签为每个标签计算相同的宽度。

如何获得不同的宽度?什么作为我的最终结果,我希望在 li 之后有 div,之前有 li 宽度...如果这有意义吗?

  <ul>

     <li style="disply:block; float:left">Some Text</li>
       <div style="width" />
     <li style="disply:block; float:left">Some More Text</li>
       <div style="width" />
     <li style="disply:block; float:left">Some Other Text</li>
       <div style="width" />

 </ul>

非常感谢您提前提供的帮助。

【问题讨论】:

  • 显示应该显示。不确定这是否是您的编码或您发布此内容时的拼写错误。

标签: jquery


【解决方案1】:

$('li').outerWidth() 将获得第一个 &lt;li&gt; 的宽度,正如您所发现的。

From the docs

获取外部宽度(包括 默认情况下的边框和填充) 第一个匹配的元素。

我们需要的是每个的宽度,所以像$.map() 这样的东西会很好地工作。这会给我们一个宽度数组

var widths = $.map($('li'), function(e) {
    return $(e).outerwidth();
});

编辑:

这个怎么样

$('li').each(function() {
    var $this = $(this);
    var width = $this.outerWidth();
    $this.after($('<div style="width:' + width + 'px" >'));
});

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2021-08-20
    • 2013-03-05
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多