0

我正在使用的 javascript 应用程序遇到一些重大问题。我希望我的窗口打开到一个封闭的信封,然后在五秒钟后变成一个打开的信封,在它的角落有一个小 1 柜台。我希望计数器每五秒钟继续向上移动一次,除非单击信封。如果单击,我希望计数重新开始。到目前为止,我只看到了我的封闭信封。我是新手,不知道我做错了什么,所以任何帮助都会很棒!
我的html:

<!DOCTYPE html>
<html>
    <head>
<script type="text/javascript" src="mail.js"></script>
    </head>
    <body>
        <img id"closed" src="closed.png" onclick="resetTimer()">
        <span id="counter"></span>
    </body>
</html>

还有我的 JavaScript:

window.onload = function(){
    var counter = 0;
    var timer = setInterval(
        function(){         
            counter++; 
            document.getElementById("demo").firstChild.nodeValue = counter;
        }, 
        5000
    );              

    function openEnvelope(){
         var img = document.getElementById("picture");
         if (counter > 1){
             img.src = "open.png"
         }
    }
    open = setTimeout("open()", 1000);

    function resetTimer(){
         clearInterval(timer);
    }
}
4

1 回答 1

1

You need to increment your counter and set the counter span to have that value :

        var counter = 0;
        //Create your timer (setTimeout will only run once, setInterval will start again once run.
        //1000 = 1 second
        var timer = setInterval(openEnvelope, 1000);

        function openEnvelope() {
            var img = document.getElementById("picture");
            var counterSpan = document.getElementById("counter");
            if (counter > 1) {
                img.src = "open.png"
                counterSpan.innerHTML = counter;
            }
            //Add 1 to Counter
            counter++;
        }

        function resetTimer() {
            clearInterval(timer);
            counter = 0;
        }

This will run your openEnvelope function every second, and if the counter value is more than 1 it will set the Img Source to be open.png and the counter span to have the counters value. On the click of the Envelope it will clear the timer and reset the counter.

And your HTML will become :

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="mail.js"></script>
    </head>
    <body>
        <img id"picture" src="closed.png" onclick="resetTimer()">
        <span id="counter"></span>
    </body>
</html>

Here is a working JSFiddle for your problem, try creating a blank page and copying the HTML straight into the <body> tag and the Javascript into <script></script> tags in the <head> of your page.

于 2013-10-01T09:22:22.913 回答