jquery addClass 和 removeClass 与 setInterval
我想每 3 秒更改一次类名。但这不起作用。我该怎么做?
$(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;
});
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;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在一行中完成此操作。使用 toggleClass:
如果你的 CSS 正确,你不需要删除
liveEvents类。只需让
liveEventsActive
类覆盖您需要的内容即可。You can do this in one line. Use toggleClass:
If you do your CSS correctly, you don't need to remove the
liveEvents
class. Just make theliveEventsActive
class overwrite what you need.每次函数运行时,您都会执行四件事,这实际上会将您带回到开始状态:
liveEvents
liveEventsActive
liveEventsActive
code>liveEvents
您想要打开/关闭这两个类,因此请查看
.toggleClass()
函数。您还需要两个选择器,一个用于选择具有liveEvents
类的元素,另一个用于选择具有liveEventsActive
类的元素。You're doing four things every time the function runs, which essentially takes you back to your start state:
liveEvents
liveEventsActive
liveEventsActive
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 theliveEvents
class and one to select elements with theliveEventsActive
class.对于您的代码,整个函数每 3 秒执行一次。添加/删除类发生在一个块中,您显然看不到区别。
jQuery 有一个 .toggleClass() 方法,该方法将相应地添加/删除指定的类:
< a href="http://jsfiddle.net/didierg/8GqXv/" rel="nofollow">演示
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:
DEMO
这将使用转换来交换您的课程,希望这会有所帮助
this will swap your classes using transitions, hope this will help