简体   繁体   中英

Add class to each div in a container after interval, and remove previous

I'm attempting to add a 'hovered' class to each <a> within a div inside a container in turn. There should be a short delay between each class being applied, and as the class is applied to the next div it should be removed from the previous. After the same delay the class should be removed from the final div.

jQuery(document).ready(function() {

    $('.banner-wrap > div > a').each(function(i){
        var row = $(this);
        setTimeout(function() {
            $('.hovered').removeClass('hovered');
            row.toggleClass('hovered');
        }, 400*i);

    });

});

This is half working - but I'm struggling to understand how to delay the first item (currently that one is getting the class on load) and also need a pointer on how to make sure it's removed after the last div has had the class for the same interval.

Here you go..

 $(document).ready(function() { var interval = 1000; var timerIds = []; var links = $('.banner-wrap > div > a'); $.each(links, function(index, value) { if (index == links.length - 1) { timerIds.push(window.setTimeout(function() { $('.hovered').removeClass('hovered'); $.each(timerIds, function(idx, val) { clearTimeout(val); }); while (timerIds.length) {timerIds.pop();} }, interval*(index + 2))); } timerIds.push(window.setTimeout(function() { $('.hovered').removeClass('hovered'); $(value).toggleClass('hovered'); }, interval*(index + 1))); }); }); 
 div {display:block;padding:1em;} a {display:block; line-height:1em; color:gray;background-color:whitesmoke;border:0.1em solid whitesmoke;transition: all 1s;} a.hovered {display:block;height:3em;line-height:3em;color:white;background-color:gray;border:0.1em solid black;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="banner-wrap"> <div> <a href="#">Link 1</a> <a href="#">Link 1</a> <a href="#">Link 1</a> <a href="#">Link 1</a> <a href="#">Link 1</a> </div> </div> 


Here is a performance test using the various $.each configurations in this consideration. http://jsperf.com/jqueryeach


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