Javascript将脚本包装成函数

时间:2014-02-04 12:46:33

标签: javascript function timer

这里我有一个简单的脚本,它是一个倒数计时器,这里是代码:

<span id="countdown" class="timer"></span>
<script>
    var seconds = 60;
    function secondPassed() {
        var minutes = Math.round((seconds - 30)/60);
        var remainingSeconds = seconds % 60;
        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds;  
        }
        document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Buzz Buzz";
        } else {
            seconds--;
        }
    }
    var countdownTimer = setInterval('secondPassed()', 1000);
</script>

现在,当我在Chrome上打开此页面时,它会立即开始倒计时,我尝试做的是让我在点击图片时开始倒计时,我该怎么做这些人?

由于

3 个答案:

答案 0 :(得分:1)

在图像的事件处理程序内启动间隔

<span id="countdown" class="timer"></span>
<img src="http://www.clker.com/cliparts/5/r/I/j/O/k/another-green-start-button.svg" id="image" />

<script>
    var seconds = 60,
        countdownTimer;

    function secondPassed() {
        var minutes = Math.round((seconds - 30)/60);
        var remainingSeconds = seconds % 60;
        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds;  
        }
        document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Buzz Buzz";
        } else {
            seconds--;
        }
    }

    document.getElementById('image').addEventListener('click', function() {
          countdownTimer = setInterval(secondPassed, 1000);
    }, false);

</script>

FIDDLE

答案 1 :(得分:0)

使用点击图片

<span id="countdown" class="timer"></span>
<img onClick="startTimer()" src="https://cdn1.iconfinder.com/data/icons/iconsweets2/40/clock_alarm.png">
<script>
    var seconds = 60;
    function secondPassed() {
        var minutes = Math.round((seconds - 30)/60);
        var remainingSeconds = seconds % 60;
        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds;  
        }
        document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Buzz Buzz";
        } else {
            seconds--;
        }
    }
    var countdownTimer;
    function startTimer(){
        countdownTimer = setInterval('secondPassed()', 1000);
    }
</script>

答案 2 :(得分:-1)

在图像上设置onclick侦听器:

<img onclick="setInterval('secondPassed()', 1000)" src="..."/>