jQuery计时器功能

时间:2011-10-24 13:00:19

标签: jquery

我有onmouseenter事件,只有当鼠标在对象内花费超过n秒时才会触发。

$('#object').live('mouseenter', function() { 

// code that will execute only if mouse spends more than n seconds

});

我很感激任何帮助。

2 个答案:

答案 0 :(得分:4)

var timeout;
$('#object').live('mouseenter', function() { 
    timeout = setTimeout(function(){
        // code that will execute only if mouse spends more than n seconds
    }, 2000);

});

$('#object').live('mouseleave', function() { 
   clearTimeout(timeout); 
});

所以例如将文本更改为“Working”并将颜色更改为红色,以下代码很好

<div id="object">Hover here and wait</div> 
<script> 
var timeout; 
var object = $("#object"); 
object.live('mouseenter', function() {  
    timeout = setTimeout(function(){ 

        object.css({'color': 'red', 'font-size': '400%'}); 
        object.html('Working'); 
    }, 2000); 
}); 

object.live('mouseleave', function() {  
   clearTimeout(timeout);  
}); 
</script>

demo

答案 1 :(得分:0)

您可以设置延迟后调用的函数,如果看到mouseleave,则取消它:

(function() {
    var timer = 0; // 0 is a safe "no timer" value

    $('#object').live('mouseenter', function() {
        // I'm assuming you don't want to stomp on an existing timer
        if (!timer) {
            timer = setTimeout(doSomething, 1000); // Or whatever value you want
        }
    }).live('mouseleave', function() {
        // Cancel the timer if it hasn't already fired
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
    })

    function doSomething() {
        // Clear this as flag there's no timer outstanding
        timer = 0;

        // Do your stuff
    }

})();