简体   繁体   English

jQuery-在mousedown上触发常规函数调用

[英]jQuery - triggering a regular function call on mousedown

I want a function to be called regularly at a given interval whilst the left mouse button is being held down over a specific element. 我希望在给定的时间间隔内定期调用某个函数,同时在特定元素上按住鼠标左键。 Is there a simple way of doing this in jQuery or should I use vanilla javascript and setInterval/setTimeout? 有没有在jQuery中执行此操作的简单方法,还是应该使用香草javascript和setInterval / setTimeout?

Thanks 谢谢

Here's a jQuery plugin that provides a mousehold event. 这是一个提供mousehold事件的jQuery插件。

http://remysharp.com/2006/12/15/jquery-mousehold-event/ http://remysharp.com/2006/12/15/jquery-mousehold-event/

If you go to the demo page and click on one of the arrows to the right of the last input box you'll see how it works. 如果转到演示页面 ,然后单击最后一个输入框右侧的箭头之一,您将看到其工作原理。

This is how I would do it: 这就是我要做的:

HTML: HTML:

<div id="box"></div>

JavaScript: JavaScript的:

var box = $('#box'),
    iv;

function foo() {
    box.append('*');    
}

box.bind('mousedown mouseup', function(e) {
    $(this).toggleClass('hold', e.type === 'mousedown');
});

iv = setInterval(function() {    
    box.hasClass('hold') && foo();
}, 1000);

So you bind a handler to both the mousedown and mouseup events, and set the hold CSS class accordingly. 因此,您将处理程序绑定到mousedownmouseup事件,并相应地设置hold CSS类。 Meanwhile, an independent timer iv will inspect whether or not the hold class is set, and call your function ( foo ) accordingly. 同时,独立计时器iv将检查是否设置了hold类,并相应地调用了函数( foo )。

Live demo: http://jsfiddle.net/simevidas/7CUFE/ 现场演示: http : //jsfiddle.net/simevidas/7CUFE/

jQuery does not provide any function watching support as a result, you could use the vanilla setTimeout function as follows: 因此,jQuery不提供任何功能监视支持,您可以按如下方式使用香草setTimeout函数:

var timer;

function functionToRun() {
    // Function code here...
    functionToRun();
}

var inFunction = function() {
    timer = window.setTimeout(functionToRun, intervalToRunFor);
}

var outFunction = function() { 
    window.clearTimeout(timer);
}

$('selector').hover(function() { inFunction, outFunction }
var mouseDown = false;

$('#yourID').bind('click', function() {
    mouseDown = true;
});

$('#yourID').bind('mouseup', function() {
    mouseDown = false;
});

setInterval('checkOut();',5000);

function checkOut() {
   if(mouseDown) alert('mouse is down! Whatup!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM