图片幻灯片显示的Javascript按钮问题

时间:2016-06-19 19:18:47

标签: javascript

我想修复按钮,以便用户可以点击它以启动红绿灯幻灯片。目前,它正在干扰循环,这意味着当用户点击按钮时,它将固定幻灯片而不是启动它。

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "traffic light_1.png"
var image2 = new Image()
image2.src = "traffic light_2.png"
var image3 = new Image()
image3.src = "traffic light_3.png"
var image4 = new Image()
image4.src = "traffic light_2.png"
</script>
</head>
<body>
<p><img src="traffic light_1.png" width="800" height="500" name="slide" /></p>

<button onclick="slideit()">Click me</button>

<p id="demo"></p>

<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<4)
                step++;
            else
                step=1;
            setTimeout("slideit()",4000);
        }
        slideit();
</script>
</body>

1 个答案:

答案 0 :(得分:0)

var img = new Image()
img.src = ...

您正在创建<img src="..." > Image()

假设您要替换 src。因此,可以使用URL设置数组:

var urls = ["img2.jpg", ..., "img1.jpg"];

为已设置的<img> ID 设置并使用document.getElementById("slide");

进行访问

然后你有这样的事情:

&#13;
&#13;
var urls = ["http://unsplash.it/300/150?image=2", "http://unsplash.it/300/150?image=3", "http://unsplash.it/300/150?image=4",
"http://unsplash.it/300/150?image=1"];

var step = 0;

function slideit() {
    var s = document.getElementById("slide");
    s.src = urls[step];
    if(step < 3) {
    	step++;
    } else {
    	step = 0;
    }
}

slideit();
&#13;
<p>
    <img id="slide" src="http://unsplash.it/300/150?image=1" width="300" height="200" name="slide" />
</p>

<button onclick="slideit()">Click me</button>
&#13;
&#13;
&#13;