您好我只是尝试在包含类前面的元素上执行每个循环但是只有第一个元素因某些原因而得到更新请帮助。可能是一个愚蠢的错误,但我无法找到它。
的jsfiddle:
HTML:
<div class="wrapper">
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
</div>
jquery的:
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
$(".front").each(function(i, e) {
topPos++;
if (i % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + " " + (leftPos - 1) * dimension;
e.style.backgroundPosition = position;
e.innerHTML = e.style.backgroundPosition;
});
}
setSlide(3,200);
的CSS:
.front{
width:200px;
height:200px;
background:url(some image);
border:1px solid black;
float:left
}
.wrapper{
overflow:hidden;
width:610px;
}
答案 0 :(得分:5)
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
$(".front").each(function(i, e) {
topPos++;
if (i % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + 'px ' + (leftPos - 1) * dimension +'px';
e.style.backgroundPosition = position;
e.innerHTML = e.style.backgroundPosition;
});
}
setSlide(3,200);
<强> THE WORKING DEMO. 强>
答案 1 :(得分:1)
好吧我已经将javascript轻微地折射成了jquery,因为你使用它并从vanilla javascript移动:
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
var front = $('.front');
$.each(front, function(index, val) {
topPos++;
if (index % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + "px, " + (leftPos - 1) * dimension + 'px';
$(this).css('backgroundPosition', position);
$(this).append(position);
});
}
setSlide(3,200);
如果您可以告诉我们您尝试使用if语句做什么,那么有助于添加背景位置... 如果你在页面中有它,你应该真的在jQuery,因为它会更快,你也应该缓存你的变量