脚本不是通过图像循环

时间:2016-06-20 08:53:43

标签: javascript html css slideshow

所以基本上应该有一个红绿灯,它应该通过CSS幻灯片放映每个图像然而它不起作用

<head>
<script type="text/javascript">
var Picture1 = new Image()
Picture1.src = "Traffic_Red.png"
var Picture2 = new Image()
Picture2.src = "Traffic_Amber.png"
var Picture3 = new Image()
Picture3.src = "Traffic_Green.png"
var Picture4 = new Image()
Picture4.src = "Traffic_Amber.png"
</script>
</head>
<body>
<p><img src="Traffic_Red.png" width="500" height="300" name="slide" /></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()",3000);
        }
        slideit();
</script>
</body>

2 个答案:

答案 0 :(得分:0)

eval("image"+step+".src");

因此,您尝试访问image1.src

var Picture1 = new Image()

...但您将其称为Picture1而不是image1

您只需要将变量名称设置为正确。

也就是说,使用eval创建变量变量非常糟糕。只需使用数组。

图片的name属性已被弃用,有利于id

setTimeout最好传递一个函数,而不是传递给它的字符串。

<p><img src="Traffic_Red.png" width="500" height="300" id="slide" /></p>

<script>
    var pictures = [new Image(), new Image(), new Image(), new Image()];
    pictures[0].src = "Traffic_Red.png";
    pictures[1].src = "Traffic_Amber.png";
    pictures[2].src = "Traffic_Green.png";
    pictures[3].src = "Traffic_Amber.png";


    var step=0;
    function slideit() {
        document.getElementById('slide").src =  pictures[step].src;
        step++;
        if (step >= 4) {
            step = 0;
        }
        setTimeout("slideit", 3000);
    }

    slideit();
</script>

答案 1 :(得分:0)

只需将Picture1,Picture2,Picture3 ....中的变量名称重命名为image1,image2,image3同样为Ex;

替换:

<head>
<script type="text/javascript">
  var Picture1 = new Image()
  Picture1.src = "Traffic_Red.png"
  var Picture2 = new Image()
  Picture2.src = "Traffic_Amber.png"
  var Picture3 = new Image()
  Picture3.src = "Traffic_Green.png"
  var Picture4 = new Image()
  Picture4.src = "Traffic_Amber.png"
</script>
</head>

使用:

<head>
    <title>Test</title>
    <script type="text/javascript">
        var image1 = new Image()
        image1.src = "Traffic_Red.png"
        var image2 = new Image()
        image2.src = "Traffic_Amber.png"
        var image3 = new Image()
        image3.src = "Traffic_Green.png"
        var image4 = new Image()
        image4.src = "Traffic_Amber.png"
    </script>
</head>

你的脚本如下:

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