gpt4 book ai didi

Javascript 计数器函数 onload 不起作用

转载 作者:行者123 更新时间:2023-11-30 15:28:59 27 4
gpt4 key购买 nike

我正在尝试修改这个 fiddle ,以便它启动计数器加载,但是当我在 body 标签上使用 onload 时,它似乎不起作用。我错过了什么?看起来代码很简单。下面是原始的 fiddle Original fiddle

var timer = document.getElementById("timer");
var start = document.getElementById("start");
var pause = document.getElementById("pause");
var resume = document.getElementById("resume");
var id;
var value = "00:00";

startTimer(m, s)

function startTimer(m, s) {
timer.textContent = m + ":" + s;
if (s == 0) {
if (m == 0) {
return;
} else if (m != 0) {
m = m - 1;
s = 60;
}
}

s = s - 1;
id = setTimeout(function() {
startTimer(m, s)
}, 1000);
}

function pauseTimer() {
value = timer.textContent;
clearTimeout(id);
}

function resumeTimer() {
var t = value.split(":");

startTimer(parseInt(t[0], 10), parseInt(t[1], 10));
}

start.addEventListener("click", function() {
startTimer(5, 0);
}, false);

pause.addEventListener("click", pauseTimer, false);

resume.addEventListener("click", resumeTimer, false);
<body onload="startTimer(5, 0);">

<p id="timer">00:00</p>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>

</body>

最佳答案

从您的代码中删除 startTimer(m, s)ms 没有定义。

<body onload="startTimer(5, 0);">

<p id="timer">00:00</p>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>

</body>

<script>
var timer = document.getElementById("timer");
var start = document.getElementById("start");
var pause = document.getElementById("pause");
var resume = document.getElementById("resume");
var id;
var value = "00:00";



function startTimer(m, s) {
timer.textContent = m + ":" + s;
if (s == 0) {
if (m == 0) {
return;
} else if (m != 0) {
m = m - 1;
s = 60;
}
}

s = s - 1;
id = setTimeout(function() {
startTimer(m, s)
}, 1000);
}

function pauseTimer() {
value = timer.textContent;
clearTimeout(id);
}

function resumeTimer() {
var t = value.split(":");

startTimer(parseInt(t[0], 10), parseInt(t[1], 10));
}

start.addEventListener("click", function() {
startTimer(5, 0);
}, false);

pause.addEventListener("click", pauseTimer, false);

resume.addEventListener("click", resumeTimer, false);
</script>

关于Javascript 计数器函数 onload 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42524739/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com