代码:
var pictures = ["url(bildes/unity.png)", "url(bildes/xna.png)", "url(bildes/bge.png)"];
var countthearray = pictures.length;
var i = 0;
function MoveOneUp(){
i++;
document.getElementById("slaideris").style.backgroundImage=pictures[i];
if (i == countthearray-1) {
i =-1;
}
}
function MoveOneDown(){
--i;
document.getElementById("slaideris").style.backgroundImage=pictures[i];
if (i<0){
i=countthearray;
}
}
我正在尝试通过附加了JS的按钮更改元素的背景图像。如果我使用函数MoveOneUp()
一切正常,但函数MoveOneDown()
似乎存在某种我不理解的问题。
每当我到达数组的最后一项时,我必须单击 2 次,然后它才返回数组长度值。有人可以解释一下问题在哪里以及如何解决吗?
在实际使用该值设置背景之前,请尝试检查边界:
var pictures = ["url(bildes/unity.png)", "url(bildes/xna.png)", "url(bildes/bge.png)"],
countthearray = pictures.length,
i = 0,
slider = document.getElementById("slaideris"); // cache the element
function MoveOneUp(){
if (i == countthearray)
i = 0;
slider .style.backgroundImage=pictures[i];
i++;
}
function MoveOneDown(){
if (i<0)
i=countthearray -1;
slider .style.backgroundImage=pictures[i];
--i;
}
删除if
块。
然后定义此帮助程序函数:
function clamp(i, c) {
return (i % c + c) % c;
}
然后,您可以在需要时访问pictures[clamp(i,c)]
。