jQuery addClass removeClass with timer

◇◆丶佛笑我妖孽 提交于 2019-12-11 15:31:45

问题


I have an issue with a 'Latest News' module. Please have a look at http://www.proudfootsupermarkets.com/ to see an example of the module (it's the div close to the top of the page which has a large image in it).

At the moment I have it set up so that when a user clicks on a tab the main article shows. The jQuery for this is:

    jQuery(document).ready(function() {

    $(".moduletable.latestnews article:first-child").addClass("atfront")

    $(".moduletable.latestnews article").click(function(){
        $(".moduletable.latestnews article").css("zIndex",1).addClass("atback").removeClass("atfront");
        $(this).css("zIndex",100).addClass("atfront").removeClass("atback");
    });
});

This is all quite simple and straight forward. The problem that I am having is that I want the articles to change automatically after a few seconds. This would then go in an infinite loop starting with article 1 and then after a couple of seconds showing article 2 etc etc...

I am sure that this is fairly simple but I have just about exhausted my knowledge of JavaScript. Thank you for any help that you are able to give :)

I have created a jsfiddle http://jsfiddle.net/Bempv/


回答1:


You can use setTimeout to change the article in front. If you select the article with the class ".atfront" and then use the .next() selector you should get the functionality you are looking for

$(function(){
    var articleToggler = function articleToggler(){
    var front = "atfront",
        back = "atback";
    return function(){
       var selection = $(".moduletable.latestnews")
                          .find("article.atfront")
                          .addClass(back)
                          .removeClass(front);
           next = selection.next("article"); 
           next = next.length ? next : $(".moduletable.latestnews")
                                   .find("article").first();
           next.addClass(front)
               .removeClass(back);
           console.log(selection.length,next[0])  


       setTimeout(articleToggler(),1000); //changes every second
    };
};

//start the rotation
(articleToggler())();
});

The setTimeout will call the function passed as the first argument once the timeout expires. The timeout argument is in miliseconds so the above code wait for 1 second before calling the function. Since the above function adds it self as the callback this will repeat indefinately



来源:https://stackoverflow.com/questions/13341945/jquery-addclass-removeclass-with-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!