简体   繁体   中英

jQuery show next image on click doesn't work with .first

I'm trying to fade into view the next image toggleImg() is called from an onClick, however when we get to the end of the list and I start from the beginning again the fade effect doesn't work.

I assume it has something to do with the way the HTML is loaded in the dom and that the last image tag has a higher priority (as its further down the dom).

Do you know why the fade effect doesn't work when we reach the bottom of the list and start from the beginning again?

 $('.next').click( function() { toggleImg(); }); function toggleImg() { //Setup vars var current = $('ul#feature-image li.current'); var next = current.next(); //tag this guy to be deleted later current.addClass('old'); //check if were at the end of the list if (next.length != 1) { current = $('ul#feature-image li').first(); current.addClass('current imgFadeIn'); } else { current.next().addClass('current imgFadeIn'); } //delete the last guy now the animation is complete setTimeout(function() { $('ul#feature-image li.old').removeClass('current old imgFadeIn'); }, 700); } 
 .next{ position:absolute; top: 0; left: 0; background: pink; padding: 10px 20px; z-index: 9999; } .imgFadeIn { animation-name: imgFadeIn; animation-duration: 400ms; animation-fill-mode: forwards; } @keyframes imgFadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } ul#feature-image { padding: 0px 0px; margin: 0px 0px; } ul#feature-image li { width: 100%; height: auto; min-height: 700px; display: none; position: absolute; } ul#feature-image li img { width: 100%; height: auto; min-height: 100%; z-index: 0; position: absolute; } ul#feature-image li.current { z-index: 99; display: block; } ul#feature-image li.current img { z-index: 50; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="feature-image"> <li class="current"><img src="http://via.placeholder.com/350x200" alt="img"></li> <li><img src="http://via.placeholder.com/300x230" alt="img"></li> <li><img src="http://via.placeholder.com/320x100" alt="img"></li> <li><img src="http://via.placeholder.com/400x250" alt="img"></li> </ul> <div class="next">next</div> 

As requested JSFiddle - https://jsfiddle.net/Lm99d6f0/1/ * Notice the fade, until the last list item

You need to add z-index to .old element.

ul#feature-image li.old {
    z-index: 98;
}

https://jsfiddle.net/Lm99d6f0/2/

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