jquery addClass and removeClass with setInterval

戏子无情 提交于 2019-12-07 07:25:45

问题


I want to change class name every 3 seconds. Bu it doesn't work. How can I do this?

$(document).ready(function() {
        function moveClass(){
            var x = $('.liveEvents');
            x.removeClass('liveEvents');
            x.addClass('liveEventsActive');
            x.removeClass('liveEventsActive');
            x.addClass('liveEvents');
       }

        setInterval(moveClass, 3000); 
        return false;
    });

回答1:


You can do this in one line. Use toggleClass:

setInterval(function(){$('.liveEvents').toggleClass('liveEventsActive')}, 3000);

If you do your CSS correctly, you don't need to remove the liveEvents class. Just make the liveEventsActive class overwrite what you need.




回答2:


You're doing four things every time the function runs, which essentially takes you back to your start state:

  • Remove class liveEvents
  • Add class liveEventsActive
  • Remove class liveEventsActive
  • Add class liveEvents

You want to toggle those two classes on/off, so take a look at the .toggleClass() function. You'll also need two selectors, one to select elements with the liveEvents class and one to select elements with the liveEventsActive class.




回答3:


With your code, the whole function is executed every 3 seconds. The add/remove class happens in one block and you obvisouly cannot see the difference.

jQuery has a .toggleClass() method that will add/remove the specified class accordingly:

function moveClass() {
    $('.liveEvents')
        .toggleClass('liveEventsActive');
}

DEMO




回答4:


$(document).ready(function() {
    function moveClass(){
        $( ".liveEvents" ).switchClass( "liveEvents", "liveEventsActive", 1000);
        $( ".liveEventsActive" ).switchClass( "liveEventsActive", "liveEvents", 1000 );
   }

    setInterval(moveClass, 3000); 
    return false;
});

this will swap your classes using transitions, hope this will help



来源:https://stackoverflow.com/questions/9099263/jquery-addclass-and-removeclass-with-setinterval

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