HTML按钮-按住按钮将重复操作 [英] HTML button- when hold the button it will repeat the action
问题描述
我是HTML的新手,并且我正在从事一个项目,该项目需要在您按住按钮时使用按钮,它将重复相同的操作.这是我得到的代码,但是没有用.
I'm new to HTML and I'm working on a project that is required to use a button when you pressed and hold it, it would repeat the same action. This is the code I got sofar but did not work.
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Button</title>
</head>
<body>
<button id = "forward" accesskey="o" onmousedown="display(1)" onmouseup="stop()">forward</button>
<script>
function stop(){
console.log(" ")
}
function display(value){
if (value == 1){
console.log("left");}}
</script>
</body>
</html>
推荐答案
您需要的是 setInterval
和 clearInterval
.
var wrapper = document.getElementById('counter');
var counter;
var count = 0;
function start() {
counter = setInterval(function() {
wrapper.innerHTML = count;
count++;
}, 500);
}
function end() {
clearInterval(counter)
}
<button onmousedown="start()" onmouseup="end()">Click and hold</button>
<p id="counter"></p>
如果您不熟悉 setInterval
和 clearInterval
,它们类似于 setTimeout
.您可以将 setInterval
分配给一个变量,稍后可以将其传递给 clearInterval
来停止该变量.这样做是将您传递的代码放入另一个堆栈中,以便您的其他代码可以继续执行,例如可以清除它的 onmouseup
事件.
If you're not familiar with setInterval
and clearInterval
, they are similar to setTimeout
. You can assign setInterval
to a variable that you can pass to clearInterval
later to stop it. What this does is it puts the code you pass into it on a different stack, so your other code can continue to execute, such as an onmouseup
event that can clear it.
https://www.w3schools.com/jsref/met_win_setinterval.asp https://www.w3schools.com/jsref/met_win_clearinterval.asp
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
这篇关于HTML按钮-按住按钮将重复操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!