在按下鼠标按钮的整个时间执行按钮事件处理程序

Execute button event handler the entire time mouse button is depressed

本文关键字:按钮 时间 执行 事件处理 程序 鼠标      更新时间:2023-09-26

我想为按钮创建一个javascript mousedown事件处理程序。当按下按钮时,我需要处理程序重复执行,直到按钮被释放(mouseup被触发)。例如,按住向上按钮应使文本框值递增,直到释放为止。

处理这个问题的最佳方法是什么?

您可以使用setInterval:http://jsfiddle.net/5wypC/1/.

var interval = null;
var i = 0;
$('button').mousedown(function() {
    clearInterval(interval); // Make sure to clear any intervals
                             // that are occasionally still running
    interval = setInterval(function() {
        $('textarea').val(i++);
    }, 100);
});
$('button').mouseup(function() {
    clearInterval(interval);
});