简体   繁体   中英

jQuery hide li elements, then fade in on button hover

I have a standard ul list which contains five li elements. After the third element, I've placed a button in the list with the CSS class .morecats .

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <button class="morecats">+</button>
    <li>4</li>
    <li>5</li>
</ul>

Using jQuery, I have hidden the first three li elements:

$('ul')
  .find('li:gt(3)')
  .hide()
  .end();

Now, I'd like jQuery to fade in and show the hidden li elements when the user hovers over the button .morecats . I'd also like a separate div called .bg to fade in/appear.

How could this be accomplished?

One way to accomplish this would be through the jQuery hover function . The official example even has a fade in and fade out example you can look at.

$(".morecats").hover(
    function(){   // When the hover begins
        $('li').slice(-2).fadeIn(500);
    }, 
    function(){   // When the hover ends
        $('li').slice(-2).fadeOut(500);
    } 
);

The slice gets the last two li elements.

Jsfiddle: http://jsfiddle.net/wDLVQ/2/

You can achive it through prevAll() jQuery function:

You can read more here - http://api.jquery.com/prevAll/

$('ul')
.find('li:lt(3)')
.hide();           //<----------------------------first 3 li hidden

$(".morecats").hover(
    function(){
        $(this).prevAll('li').fadeIn(500); // when hover the button fadeIn the 
        $('.bg').fadeIn(500);              // hidden li and .bg div.
    },
    function(){ 
        $(this).prevAll('li').fadeOut(500); // used it to fadeout the first 3
    }                                       // lis again.
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM