开发者

Jquery parent element is hidden with child element on mouseout

I 开发者_StackOverflow社区am having a problem where the parent list element is being hidden along with the child, when I only want the child to hide on mouseout. Below is my code, any help is greatly appreciated!

$(document).ready(function(){
    $('#home').hover(
        function() {
            $(this).children().stop().show();
        },
        function() {
            $(this).children().stop().hide();
        }
    );
});


I think I might know what the issue is (having the list markup would help).

You're hiding all of the children of the parent list element, which will "hide" the parent element, since it has nothing to display:

<div>
    <ul id="home">
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
    <ul>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
    <ul>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
</div>

$(document).ready(function(){
    $('#home').hover(
        function() {
            $(this).children().stop().show();
        },
        function() {
            $(this).children().stop().hide();
            console.log(this);
        }
    );
});

http://jsfiddle.net/sK36C/2/

Use Chrome Console or Firebug in Firefox to view the HTML tab for that element after it's hidden, and you'll notice each of the LIs for the UL#home are display: none. There is nothing to display in the UL, so it appears to have disappeared.

Here's another demonstration where I tell it to skip the :first child and hide the rest:

<div>
    <ul id="home">
        <li>This is #home text</li>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
    <ul>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
    <ul>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
    </ul>
</div>

$(document).ready(function(){
    $('#home').hover(
        function() {
            $(this).children(':not(:first)').stop().show();
        },
        function() {
            $(this).children(':not(:first)').stop().hide();
            console.log(this);
        }
    );
});

http://jsfiddle.net/sK36C/3/

Note how the first element isn't hidden, and the UL#home is still visible.

See: http://api.jquery.com/children/


Better you can have this using simple CSS:

HTML:

<div>
    <ul id="home"><p>MENU</p>
        <li>li1</li>
        <li>li2</li>
        <li>li3</li>
        <li>li4</li>
    </ul>  
</div>

CSS:

#home:hover li{
    display: block;
}

#home li {
 display: none;
}

Fiddle1

Incase if you want to try using jQuery

When you use jQuery try doing it using .toggle()

$(document).ready(function(){
    $('#home p').hover(
        function(e) {
            $(this).parent().children(':not(:first)').toggle();
           ;
        }
    );
});

Fiddle2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜