我想循环遍历div中的所有图片并设置“左”和“#”;比之前图像的左侧设置多50px。不过,我在语法方面遇到了麻烦。我如何指出第i个img?
HTML:
<div class="col-md-5 leftimage">
<div class="imageholder">
<img src="img/photo1.jpg" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
<div class="imageholder">
<img src="img/photo2.jpg" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
<div class="imageholder">
<img src="img/photo3.jpg" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
</div>
的CSS:
.leftimage {
position: relative;
}
.leftimage .imageholder {
position: absolute;
top: 0px;
left: 0px;
cursor: pointer;
width: 300px;
width: max-content;
}
.imageholder:nth-child(1) {
/*left: 100px;*/
}
.imageholder:nth-child(2) {
/*left: 50px;*/
}
.caption {
color: gray;
font-size: 80%;
padding: 10px;
}
jquery的:
for (var i = 0; i<$('.imageholder img').length; i++) {
$('.imageholder img')[i].css('left', i*50 + 'px'); //this syntax isn't right
}
答案 0 :(得分:3)
如果您已经在使用jQuery,最好使用.each()
功能。
$(".leftimage > div").each(function(index){
$(this).find("img").css("left", index*50 + "px");
});
以下是一个例子:
$(".leftimage > div").each(function(index){
$(this).find('img').css("left", index*50 + "px");
$(this).find('.caption').text(index*50 + "px");
});
&#13;
.leftimage {
position: relative;
}
.leftimage .imageholder {
position: relative;
top: 0px;
left: 0px;
cursor: pointer;
width: 300px;
width: max-content;
}
.leftimage .imageholder img {
height:100px;
width:300px;
}
.caption {
color: gray;
font-size: 80%;
padding: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="leftimage">
<div class="imageholder">
<img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
<div class="imageholder">
<img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
<div class="imageholder">
<img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
<div class="imageholder">
<img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" />
<div class="caption">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </div>
</div>
</div>
&#13;
答案 1 :(得分:0)
for (var i = 0; i<$('.imageholder img').length; i++) {
$($('.imageholder img')[i]).css('left', i*50 + 'px'); //this syntax isn't right
}
可以做到这一点