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

ctrmrzij  于 2023-04-28  发布在  Java
关注(0)|答案(5)|浏览(122)

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

wpx232ag

wpx232ag1#

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

JS

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

Working Fiddle

brccelvz

brccelvz2#

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>
ktca8awb

ktca8awb3#

试试这个
将相应的鼠标事件添加到以下函数

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

uklbhaso4#

从 www.example.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>');
});

完整的url:http://api.jquery.com/mousedown/

pxy2qtax

pxy2qtax5#

使用setInterval()可以在鼠标按下之前一直执行代码,使用clearInterval()可以在鼠标释放时停止setInterval()函数。

var id;
window.onmousedown = () => {
    console.log(“holding..”)//Since setInterval doesn’t start
    //immediately and causes clearInterval to execute first

    id=setInterval(()=>{
        console.log("holding...")
    },300)
}
window.onmouseup = () => {
    clearInterval(id)
    console.log("released...")
}

相关问题