我知道'mousedown'是用户按下鼠标时,'mouseup'是用户释放鼠标时。但是我想在用户按下鼠标并按住它直到它释放后听这个事件。有什么想法吗?
答案 0 :(得分:5)
如果您想要保持状态,那么当您处于 mousedown 事件状态一段时间时,它将处于状态。当您按 mousedown 而不是 mouseup 时,会出现此状态。因此,您需要获取一个记录事件当前状态的变量。
<强> JS 强>
$('div').on('mousedown mouseup', function mouseState(e) {
if (e.type == "mousedown") {
//code triggers on hold
console.log("hold");
}
});
<强> Working Fiddle 强>
答案 1 :(得分:4)
试试这个
将相应的鼠标事件添加到以下功能
mouse = false;
function mousedown()
{
mouse = true;
callEvent();
}
function mouseup()
{
mouse =false;
}
function callEvent()
{
if(mouse)
{
// do whatever you want
// it will continue executing until mouse is not released
setTimeout("callEvent()",1);
}
else
return;
}
答案 2 :(得分:2)
来自jquery.com:
HTML:
<p>Press mouse and release here.</p>
脚本:
$("p").mouseup(function(){
$(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
$(this).append('<span style="color:#00F;">Mouse down.</span>');
});
答案 3 :(得分:1)
var setint = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
clearInterval(setint);
val = 0;
setint = setInterval(function () {
$("#putdata").val(++val);
console.log("mousehold");
},50);
});
$('#hold').on("mouseleave mouseup", function () {
val = 0;
$("#putdata").val(val);
clearInterval(setint);
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html>