<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
<a href="javascript:changeBGImage(2)">Change</a>
</body>
抱歉,我不知道我应该如何在这里正确地集成代码 - 但是它仍然有效。我想在这里做什么:更改背景(有效)而不是添加加一到后台计数器,以便下次单击链接时,下一个背景显示(这不起作用)。它应该很简单,但我无法弄明白......
答案 0 :(得分:1)
使用从0到3的静态计数器。
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
答案 1 :(得分:0)
您的代码中存在一些问题
backImage = backImage++;
不会按预期增加backImage
。语法应该只是backImage++;
另外,要设置背景图片,您需要document.body.style.background
或document.body.style.backgroundImage = url(...)
修改的
除了通过点击处理程序在背景中循环之外,如果您还需要设置初始背景,请尝试下面的操作,并在window.onload
中设置初始背景。
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);