【问题标题】:Calculate total width of child elements in more than one class using jquery使用jquery计算多个类中子元素的总宽度
【发布时间】:2012-11-14 21:54:23
【问题描述】:

我有以下代码

 <span class="numbers">
    <a href="#">20</a>, <a href="#">50</a>, <a href="#">100</a>
 </span>

“数字”类是绝对位置元素,它在页面中使用多次。

类“数字”中的内容将动态变化。所以我需要将孩子的总宽度应用到它的父容器

我试过这段代码,但没有用。

var totalWidth = 0;
$(".numbers").children('a').each(function() {
      totalWidth = totalWidth + $(this).width();
      $('.numbers').each(function(){$(this).css("width", totalWidth);});
});

但我得到的 totalWidth 值仅为 0。有没有人可以帮忙............?

请看http://jsfiddle.net/contactsreejesh/xP3mn/6/

【问题讨论】:

  • 您确定为此需要 javascript 吗?使 a-tags 块并浮动到左侧,并且父容器应随着内容的变化而调整大小。
  • 不,因为我在我的页面中多次使用“.numbers”。所以它的宽度应该是动态变化的。 & 最重要的是它的位置:绝对元素。
  • 您的代码实际上对我有用 - 您能否解决问题或将我们链接到实时页面?
  • 嗨,我已经设置了一个 jsFiddel,请看。 jsfiddle.net/contactsreejesh/xP3mn
  • @sri 您的代码在 the fiddle 上为我工作。

标签: jquery-ui jquery jquery-selectors


【解决方案1】:

首先,您需要遍历所有 numbers 元素。然后在该循​​环中,循环属于每个人的孩子numbers span

$('.numbers').each(function() {
    var totalWidth = 0;
    /* "this" in this loop is the current numbers span*/
    var $self=$(this) 
   /* loop over all the children of this element*/
    $self.children('a').each(function() { 
        /* "this" in current loop is an A tag*/
        totalWidth += $(this).width();      
    });

    /* now set width*/
    $self.width( totalWidth)

})

此语句将影响整个页面中所有具有该类的元素,并且它们都将具有相同的宽度

$('.numbers').width(totalWidth); 

【讨论】:

  • 非常感谢。你的代码对我来说很完美。我只是在它周围玩。 jsfiddle.net/xP3mn/9
【解决方案2】:

根据here,这对我有用。

var w = 0;
$('.numbers').find('a').each(function(){
    w += $(this).width();
});​​​​​​

【讨论】:

    【解决方案3】:

    检查这个小提琴http://jsfiddle.net/FGmYU/

    变化是这样的:

    totalWidth += $(this).width();
    

    输入显示计算出的宽度为 56。

    【讨论】:

    • 这不是问题。查看您的答案以避免被否决
    • 似乎是我回答了这个问题。不小心提交了,如果还是不对,对不起。
    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2011-07-16
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多