【问题标题】:javascript change the animation sequence without inputjavascript无需输入即可更改动画序列
【发布时间】:2016-07-12 11:46:17
【问题描述】:

我正在寻找的是可以添加到我的代码中的东西,它会改变我的动画并让一系列光在没有用户输入的情况下自动亮起..

到目前为止,这是我的代码,我需要将其从按钮单击功能更改为自动灯光序列的代码。

<h1>Changing HTML images</h1>
<p> Click the button to change the Traffic Lights </p>
<img id="myImage" onclick="changeimage()" src="red.jpg" width="100" height="180"> 

<button type ="button"
onclick="changeimage()">Change the traffic light</button>

<script>
var counter = 0
var image = ["red.jpg","redandorange.jpg","orange.jpg","green.jpg"]

function changeimage () {

    window.alert(counter)
    counter++

    if(counter > 3 ){
        counter = 0
    } 
    document.getElementById('myImage').src=image[counter]
}

</script>
<body>
</body>
</html>

【问题讨论】:

  • 这很简单 - setInterval( changeimage, 1000 );
  • 就在你的函数结束之后。

标签: javascript input task sequence light


【解决方案1】:

您可以使用setInterval(method, intervalTime)setTimeout(method, waitTime)

在您的具体情况下,最简单的方法是使用setInterval。例如:

setInterval(changeimage, 500);

在更复杂的情况下,您可能希望使用setTimeout 并自己重新启动它。这将确保在方法的完成和以下执行的开始之间有一个指定的最短时间。例如:

var next = function() {
  changeimage();
  setTimeout(next, 500);
};
next();

【讨论】:

    【解决方案2】:

    如果您询问如何在没有用户输入的情况下发生函数调用或事件,您可能会问什么。

    首先,如果您不需要事件并查看您不需要的代码

    在脚本的末尾

    // intervals create an idel wait loop and give you a handle to it
    // first argument function to run on loop fire
    // second argument time the idle wait is to wait before firing in milliseconds
    var IntervalH = setInterval(changeImage,30*1000)
    

    如果您想清理您的代码并使其不发生冲突,我会将其更改为使用闭包。

    (function ImageRotationClosure(){
        var counter = 0
        var secondsWait = 10;
        var image = ["red.jpg","redandorange.jpg","orange.jpg","green.jpg"]
    
        setInterval(function changeimage() {
            counter++
            if(counter > 3 ){
                counter = 0
            } 
            document.getElementById('myImage').src=image[counter]
        }, secondsWait*1000);
    })();
    

    这不仅使您的代码更小,而且使其安全,因为闭包中的 var 仅用于闭包而不是全局范围 E.G 窗口,因此它会阻止用户使用浏览器控制台(Firebug、WebKit 开发工具)和 url 注入 E.G javascript:images.push("somefile.jpg"); 以免弄乱你的滑块,比如一个狡猾的插件或用户决定插入浏览器的任何其他东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-18
      • 2022-07-06
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2018-09-22
      相关资源
      最近更新 更多