在我的项目中,我需要在mouseup事件中执行一些操作,但前提是他的mousedown后至少有一秒钟。 我试过这个:
$('*').on('mousedown', function (e) {
// make sure the event isn't bubbling
if (e.target != this) {
return;
}
//some code
}
var delay = 1000;
var timeout = null;
$(window).on('mouseup', function (e) {
clearTimeout(timeout);
timeout = setTimeout(function(){
// do something
},delay);
});
但是以这种方式,mouseup事件与mousedown没有关联,而是与他自己相关。 如何确保我的代码仅在用户在保持至少一秒后释放鼠标按钮时执行?
感谢所有
答案 0 :(得分:2)
Hook mousedown并记录它发生的时间:
var mousedown;
$(document).on("mousedown", function() {
mousedown = Date.now();
});
钩住鼠标,看看它是否已经至少一秒钟了:
$(document).on("mouseup", function() {
var elapsed = Date.now() - mousedown;
mousedown = undefined;
if (elapsed >= 1000) {
// A second or more
}
});
var mousedown;
$(document).on("mousedown", function() {
mousedown = Date.now();
snippet.log("Down at " + new Date().toISOString());
});
$(document).on("mouseup", function() {
var elapsed = Date.now() - mousedown;
snippet.log("Up at " + new Date().toISOString());
mousedown = undefined;
if (elapsed >= 1000) {
// A second or more
snippet.log("A second or more (" + elapsed + ")");
} else {
snippet.log("Less than a second (" + elapsed + ")");
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
在上面我在document
上挂了mousedown,但是如果你有充分的理由在你的问题中将它挂在每个单独的元素上,你可以根据需要进行调整。
在真正的旧浏览器上,Date.now
不存在。您可以轻松地将其填充:
if (!Date.now) {
Date.now = function() {
return +new Date();
};
}