如何隐藏鼠标悬停时的所有元素

How to hide all elements on mouse over

本文关键字:元素 悬停 鼠标 何隐藏 隐藏      更新时间:2023-09-26

我有一段代码,它隐藏了列表中所有奇数和偶数元素,除了前两个元素外,我想隐藏其他4个元素。下面是我的代码:

<body>
    <ul>
        <li>Milk</li>
        <li>White</li>
        <li>Carrots</li>
        <li>Orange</li>
        <li>Broccoli</li>
        <li>Green</li>
    </ul>
    <script>
        $( "li" )
            .filter( ":odd" )
            .hide()
            .end()
            .filter( ":even" )
            .hover(function() {
                $( this )
                    .toggleClass( "active" )
                    .next()
                    .stop( true, true )
                    .slideToggle();
            });
    </script>
</body>

建议我怎么做

使用gt() selector来实现:

$( "li:gt(1)" )
.filter( ":odd" )
.hide()
.end()
.filter( ":even" )
.hover(function() {
  $( this )
    .toggleClass( "active" )
    .next()
      .stop( true, true )
      .slideToggle();
});
<<p> 小提琴演示/strong>

阅读更多关于 gt ()

试试这个

 $('.MainUl').find('li:first').hover(function() {
     $('.MainUl').find('li').not($(this)).not($(this).next("li")).hide();
 });
 $('.MainUl').find('li:first').next("li").hover(function() {
     $('.MainUl').find('li').not($(this)).not($(this).prev("li")).hide();
 });

小提琴演示http://jsfiddle.net/gT2H6/1/