Jquery .on(“mouseenter”) - 等待2秒然后再做动作

时间:2012-01-26 20:49:56

标签: jquery

当您将鼠标悬停在div上时,我有一个显示隐藏文字的脚本。但是我希望它延迟2秒,如果用户在2秒之前将鼠标移开,我想要什么都不显示。

我该怎么做?

我拥有的内容: http://jsfiddle.net/ZhrJT/

-

HTML:

<body>
    <div>hover this</div>
    <p class="hidden">unhidden!!</p>
</body>

JS:

$("body").on("mouseenter", "div", function(){
    $("p").removeClass("hidden");
}).on("mouseleave", "div", function(){
    $("p").addClass("hidden");
});

CSS:

div {
    background-color:red;
    height:100px;
}

p.hidden {
    display:none;  
}

p {
    background-color:yellow; 
    height:100px;   
}

2 个答案:

答案 0 :(得分:35)

var timer;
$("body").on("mouseenter", "div", function(){
    timer = setTimeout(function () {
        $("p").removeClass("hidden");
    }, 2000);
}).on("mouseleave", "div", function(){
    clearTimeout(timer);
    $("p").addClass("hidden");
});

你去,这很容易。只需设置一个超时,它会在运行时隐藏元素,如果用户mouseleave是元素,则取消超时。

答案 1 :(得分:5)

使用setTimeout / clearTimeout。像这样:

$("body").on("mouseenter", "div", function(){
    $(this).data('timeout', setTimeout(function(){
       $("p").removeClass("hidden");
    }, 2000));
}).on("mouseleave", "div", function(){
    clearTimeout($(this).data('timeout'));
    $("p").addClass("hidden");
});