jQuery hide(),delay()和clearTimeout()没有按预期工作

时间:2014-01-20 07:06:17

标签: javascript jquery html css

我希望如果用户在.userNames上方悬停,.details会在稍微延迟后滑出,并且当鼠标离开.details时也希望hide()显示.userNames经过一点延迟之后。这很有效。现在我希望.details留下来,如果鼠标进入它但它仍然消失。

Obsv:当鼠标悬停时,Facebook的用户名就是一个很好的例子。

HTML code:

<div class = 'posts'>
<p class = 'userNames'> Yax </p>
<div class = 'details'> 
    <p> Full Name </p>
    <p> Birthday </p>
    <p> Age </p>
</div>
</div>

jQuery的:

$(document).ready(function(){
    $('.details').hide();
    $(document).on('mouseenter', ".userNames", function () {
        var $this = $(this);
        $.data($this, 'timer', setTimeout(function(){
            $this.parents('.posts').find('.details').slideDown(100);
        },900));
    });
    $(document).on('mouseleave', ".userNames", function () {
        var $this = $(this);
        $this.parents('.posts').find('.details').delay(800).hide(100);
    });
    $(document).on('mouseenter', ".details", function () {
        var $this = $(this);
        var $dataTime = $this.parents('.posts').find('.userNames');
        clearTimeout($.data($dataTime, 'timer'));
    });
    $(document).on('mouseleave', ".details", function () {
        var $this = $(this);
        $this.hide();
    });
});

提前谢谢。

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,可以很好地工作和简化你的jQuery:

$(document).ready(function(){
    $('.details').hide();
    $('.userNames').mouseenter(function () {
        $('.details').delay(900).slideDown(100);
    });

    $('.userNames').mouseleave(function () {
        $('.details').delay(800).hide(100);
    });

    $('.details').mouseenter(function () {
        $(this).stop(true, true);
    });

    $('.details').mouseleave(function () {
        $(this).hide(100);
    });
});

Try it here

答案 1 :(得分:1)

尝试

$(document).ready(function () {
    $('.details').hide();
    $(document).on('mouseenter', ".userNames", function () {
        var $this = $(this),
            $post = $this.closest('.posts');
        $post.data('timer', setTimeout(function () {
            $post.find('.details').stop(true, true).slideDown(100);
        }, 900));
    });
    $(document).on('mouseleave', ".userNames", function () {
        var $this = $(this),
            $post = $this.closest('.posts');
        clearTimeout($post.data('timer'));
        $post.data('timer', setTimeout(function () {
            $post.find('.details').stop(true, true).delay(800).hide(100);
        }, 900));
    });
    $(document).on('mouseenter', ".details", function () {
        var $this = $(this),
            $post = $this.closest('.posts');
        clearTimeout($post.data('timer'));
        $this.stop(true, true)
    });
    $(document).on('mouseleave', ".details", function () {
        var $this = $(this);
        $this.hide();
    });
});

演示:Fiddle