我有一个带有按钮的网页,该按钮链接到某个功能,并使用onclick在每次按下时更新数字值。我希望能够按住按钮并每隔200 ms左右递归更新一次,直到按钮被释放。我找到了一些使用jquery来实现此目的的方法,但我想知道是否只使用本机JavaScript库是可能的吗?
答案 0 :(得分:2)
是的,这是可能的。 jQuery是用原生JavaScript编写的,所以jQuery可以做任何事情,JavaScript可以做。
代码:
var button = document.getElementById('inc');
var span = document.getElementById('val');
var val = 0;
var pressed = false;
var inc = function () {
if (pressed) {
val++;
}
span.textContent = val;
setTimeout(inc, 200);
};
button.addEventListener('mousedown', function () {
pressed = true;
});
document.body.addEventListener('mouseup', function () {
pressed = false;
});
inc();
答案 1 :(得分:0)
Some Guy提出的
略有不同的版本var button = document.getElementById('inc');
var span = document.getElementById('val');
var val = 0;
var interval = null;
var inc = function () {
span.textContent = ++val;
};
button.addEventListener('mousedown', function () {
interval = setInterval(inc,200);
inc();
});
document.body.addEventListener('mouseup', function () {
window.clearInterval(interval);
});