Mouseleave在悬停时未按预期工作

时间:2015-09-23 20:42:00

标签: jquery

我在“a href”标签中有一个项目列表:

<a href="#something" class="list-item">
    <div>Title</div>
    <div>Subtitle</div>
</a>
<div class="description hide">
    This text description is hidden on default
</div>

<a href="#somethingelse" class="list-item">
    <div>Title</div>
    <div>Subtitle</div>
</a>
<div class="description hide">
    This text description is hidden on default
</div>

<a href="#anotherlink" class="list-item">
    <div>Title</div>
    <div>Subtitle</div>
</a>
<div class="description hide">
    This text description is hidden on default
</div>

...


<div id="area-for-descriptions">

    <!-- Here the descriptions will be detached and appended on mouse on and and on mouse off they will return back where they were in the beginning -->

</div>

我的css:

.hide { display: none; }
.show { display: block; }

我目前的jQuery代码:

$(document).ready(function(){

    $(document).on('mouseenter', 'a.list-item', function() {
            var currentItem = $( this ).next(); 
            currentItem.detach().appendTo('#area-for-descriptions');
            currentItem.removeClass('hide');
            currentItem.addClass('show');
    });
    $(document).on('mouseleave', 'a.list-item', function() {
        var currentItem = $( this );
        $('#area-for-descriptions a.list-item').detach().appendTo(currentItem);
    });

});

但只有mouseenter工作正常。 Mouseleave不工作,它会混淆我的代码。

知道如何改变我当前的代码,所以mouseleave也在工作吗?

我需要将描述恢复到原来的位置并将其隐藏在类中,以便将其隐藏在html代码中与开头相同的位置(在将鼠标悬停在项目之前)

1 个答案:

答案 0 :(得分:1)

无需移动元素,只需在mouseenter上克隆它,然后将其放在#area-for-descriptions并在mouseleave上清空#area-for-descriptions

$(document).ready(function(){

    $(document).on('mouseenter', 'a.list-item', function() {
        $( this ).next().clone().removeClass('hide').appendTo('#area-for-descriptions');
    }).on('mouseleave', 'a.list-item', function() {
        $('#area-for-descriptions').empty();
    });

});

Demo

顺便说一句,在使用detach()之前无需appendTo()

相关问题