使用jquery计算类,然后将该值乘以该类的宽度

时间:2015-03-18 08:33:08

标签: javascript jquery html css

我需要一些关于如何设置包装器宽度的帮助,以了解我的内容有多少个类。

我有一些小提琴here可以获得类的值,但我不知道如何实现它以使我的宽度乘以该类匹配的数量。

CONTENT: 
<div id='myDiv'>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>
 <img src='' class='class' />


CSS:
#myDiv { width: 200px; border: 1px solid red; height: 200px; }
.class { width: 200px; border: 1px solid blue; height: 200px; }


SCRIPT:
var numItems = $('#myDiv .class').length;
alert(numItems);

现在我需要做的是内容上的每个.class。我需要将它乘以#mydiv的宽度。在这种情况下,我需要一个宽度为600px的#myDiv css

- 更新

我现在有计数查询问题是它在小提琴上工作但是当我把它转移到我的本地时它不起作用。

FIddle Here

1 个答案:

答案 0 :(得分:2)

var numItems = $('#myDiv .class').length; //get the number of .class in #myDiv
var orig_width = $('#myDiv').width(); //get the original width of #myDiv
//use .outerWidth() here when you want to include padding and border
var new_width = numItems*orig_width; //multiply it with the number of .class

$('#myDiv').css('width', new_width+'px'); //set the new width to #myDiv

Demo

<强>参考

.width()

.outerWidth()

.css