jQuery 在网站上收听鼠标保持事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18584389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:00:01  来源:igfitidea点击:

listen to mouse hold event on website?

javascriptjquery

提问by user2268624

I know 'mousedown' is when user press the mouse, 'mouseup' is when user release the mouse. But I want to listen the event after user press the mouse and hold it until it release. Any ideas?

我知道 'mousedown' 是用户按下鼠标时,'mouseup' 是用户释放鼠标时。但是我想在用户按下鼠标并按住它直到它释放后监听事件。有任何想法吗?

采纳答案by Mr_Green

If you want the holdstate then it will be the state when you are in mousedownevent state for a while. This state exists when you press mousedownbut not mouseup. Hence you need to take a variable which records the current state of the event.

如果您想要保持状态,那么它将是您处于mousedown事件状态一段时间时的状态。当您按下mousedown而不是mouseup时,此状态存在。因此,您需要获取一个记录事件当前状态的变量。

JS

JS

$('div').on('mousedown mouseup', function mouseState(e) {
    if (e.type == "mousedown") {
        //code triggers on hold
        console.log("hold");
    }
});

Working Fiddle

工作小提琴

回答by Shadow

Try this

尝试这个

Add respective mouse events to folowing functions

将相应的鼠标事件添加到以下功能

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;
}

回答by shekhar kumar

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>

回答by Roy M J

From jquery.com :

来自 jquery.com :

HTML :

HTML :

<p>Press mouse and release here.</p>

Script:

脚本:

$("p").mouseup(function(){
    $(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
    $(this).append('<span style="color:#00F;">Mouse down.</span>');
});

Full url : http://api.jquery.com/mousedown/

完整网址:http: //api.jquery.com/mousedown/