Jquery 悬停取消操作


当您

将鼠标悬停在另一个 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/

任何帮助,不胜感激。

您正在寻找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'));
});

最新更新