fiddle - http://jsbin.com/AYeFEHi/1/edit
谁能解释一下为什么这不起作用? (在 Linux 上运行 Chromium)
我尝试仅在按钮按下 2 秒时执行警报框,如果不是,则清除超时功能。
<!DOCTYPE html>
<html>
<head>
<title>Testing onmousedown setTimeout alert</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script type='text/javascript'>
function call() {
alert('Hello World!');
}
$("#alertme").on('mousedown touchstart', function() {
setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(call, 0);
});
</script>
</head>
<body>
<button id="alertme">Alert me</button>
</body>
</html>
最佳答案
这不是 clearTimeout
的工作原理。您需要将 setTimeout
返回的值传递给它。
function call() {
alert('Hello World!');
}
var callTimeout = null; // hold onto the identifier for the timeout
$("#alertme").on('mousedown touchstart', function() {
callTimeout = setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(callTimeout); // clear the timeout identifier we saved.
});
您可能希望将其包装在 jQuery 页面就绪回调中,以便脚本可以位于页面上的任何位置:
$(function() {
var call = function() {
alert('Hello World!');
}
var callTimeout = null;
$("#alertme").on('mousedown touchstart', function() {
callTimeout = setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(callTimeout);
});
});
关于javascript - SetTimeout 未针对 mousedown/touchstart 函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750857/