0

当您将鼠标悬停在另一个 DOM 元素上时,我想显示一个 div,但是如果您在显示 div 之前移动鼠标,我想取消此操作。到目前为止,这就是我所拥有的

HTML

<div id="msg">
    <a href="#" id="33"> HERE </a>
</div>

JS

var timer;
$("body").on('mouseenter', '#msg a',function(){
    var userHover = $(this).attr("id");
    timer = setTimeout(function () {
        alert(userHover);   
    }, 1000);
}).on('mouseleave', '#msg a', function(){

});

http://jsfiddle.net/Nyrdz/

任何帮助表示赞赏。

4

1 回答 1

3

您正在寻找clearTimeout()

var timer;
$("body").on('mouseenter', '#msg a', function(){
    var userHover = $(this).attr("id");
    timer = setTimeout(function () {
        alert(userHover);   
    }, 1000);
}).on('mouseleave', '#msg a', function(){
    clearTimeout(timer);
});

但是,如果您有多个匹配的元素#msg a,我强烈建议您将timer值存储在特定于元素的数据中。

$("body").on('mouseenter', '#msg a', function(){
    var userHover = $(this).attr("id");
    $(this).data('timer', setTimeout(function () {
        alert(userHover);   
    }, 1000));
}).on('mouseleave', '#msg a', function(){
    clearTimeout($(this).data('timer'));
});
于 2013-02-02T12:36:29.243 回答