在网站上听鼠标举办活动?

时间:2013-09-03 05:00:24

标签: javascript jquery

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

4 个答案:

答案 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>');
});

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

答案 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>

相关问题