1
<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>

抱歉,我不明白我应该如何在此处正确集成代码 - 希望它仍然有效。我想在这里做什么:更改背景(有效)而不是在背景计数器上加一,以便下次单击链接时显示下一个背景(无效)。它应该很简单,但我还是想不通......

4

2 回答 2

1

使用从 0 计数到 3 的静态计数器。

var cnt = 0;

function changeBGImage(){
  if (document.body){
    document.body.background = backImage[cnt];
    cnt = (cnt+1) % 4; // mod 4
  }
}
于 2012-11-17T12:44:11.163 回答
0

您的代码中有几个问题

backImage = backImage++;

不会backImage像您期望的那样增加。语法应该很简单backImage++;

此外,要设置您需要的背景图像document.body.style.backgrounddocument.body.style.backgroundImage = url(...)

编辑

除了通过点击处理程序在背景中循环之外,如果您还需要设置初始背景,请尝试以下类似的操作,初始背景设置为window.onload.

jsFiddle在这里

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);
​
于 2012-11-17T13:04:28.953 回答