我很确定这对你来说是一个非常简单的答案jQuery wizzes,而且我也很漂亮,这涉及到某种循环.
我试图在两个单独的div上执行基本相同的计算,但是根据找到的图像数量为每个id分配不同的CSS宽度值.我正在执行的计算与我的问题无关,但无论如何我都将它们放入,因为它是我正在使用的实际代码.
这是标记......
<div id ='test1' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
<div id ='test2' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
下面是我目前的jQuery,它运行正常,但它效率低下,因为我必须为每个添加的div编写另一块代码.我如何标准化它,以便它通过目标类运行每个div?谢谢
/* Measure the width of each image. */
test1 = $('#div1 .scrolling img').width();
test2 = $('#div2 .scrolling img').width();
/* Find out how many images there are. */
test1img = $('#div1 .scrolling img').length;
test2img = $('#div2 .scrolling img').length;
/* Do the maths. */
final1 = (test1 * test1img)*1.2;
final2 = (test2 * test2img)*1.2;
/* Apply the maths to the CSS. */
$('#div1 .scrolling').width(final1);
$('#div2 .scrolling').width(final2);
Run Code Online (Sandbox Code Playgroud)
Nie*_*els 42
像这样:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
Run Code Online (Sandbox Code Playgroud)
该$(this)指当前.target将通过环接.在此.target我正在寻找.scrolling img并获得宽度.然后继续......
宽度不同的图像
如果要计算所有图像的宽度(当它们具有不同的宽度时),您可以这样做:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95177 次 |
| 最近记录: |