Jquery:具有相同父类和子类的子div的不同宽度,基于子div的数量

时间:2014-11-05 14:57:18

标签: javascript jquery html css

Noob在jquery,并继续努力隔离div。

有一些父div有不同数量的子div。尝试根据每个父div中的子div数设置子divs宽度。我的脚本一直在计算所有,而不是每个父母分开。

html就是

<div class="parent">
 <div class="child"></div>
 <div class="child"></div>
</div>
<div class="parent">
 <div class="child"></div>
 <div class="child"></div>
 <div class="child"></div>
</div>

和jquery

$(".parent").each(function(){  
  var prodchildren = $(".parent").children().length;
   if (prodchildren > 1) { $(".child").css('width','49%'); }
   if (prodchildren > 2) { $(".child").css('width','33%'); }
   if (prodchildren > 3) { $(".child").css('width','24.5%'); }
   if (prodchildren > 4) { $(".child").css('width','19.5%'); }
});

3 个答案:

答案 0 :(得分:3)

使用$(this)获取迭代中的当前项目。

$(".basecollections").each(function(){  
  var prodchildren = $(this).children().length;
   if (prodchildren > 1) { $(".product777").css('width','49%'); }
   if (prodchildren > 2) { $(".product777").css('width','33%'); }
   if (prodchildren > 3) { $(".product777").css('width','24.5%'); }
   if (prodchildren > 4) { $(".product777").css('width','19.5%'); }
});

答案 1 :(得分:2)

首先,您的HTML和JS不匹配。不过,这是一种在jQuery中实现它的方法,而且非常简单。对于以下HTML:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>
<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

您可以使用此脚本:

$(".parent").each(function(){
    // instead of using if, why don't you just calculate it?
    // first, check the width of a child by dividing 100 by the amount of children
    var child_width = 100 / $(this).children().length;
    // then, round it to the below number so you get a nice round number and the total doesnt exceed 100 
        child_width = Math.floor(child_width);
    // the $(this) selector represents the current .parent
    $(this).children().css("width", child_width + "%");
})

答案 2 :(得分:0)

我猜,100%的宽度不应该只是按孩子的数量来划分。 既然可以使用百分比的十进制数字,我会计算这一切,包括0.5%的余量(猜测这是whaaaaz想要的)。

所以css中的样式:

.parent > .child {margin-left:0.5%}
.parent > .child:last-child {margin-right:0.5%}

并用jquery计算:

$(".parent").each(function(){
    var children = $(this).children().length;
    var child_width = ((100-0.5-(0.5*children)) / children).toFixed(3);
    $(this).children().css("width", child_width + "%");
})