如何使用jquery每5秒更改一次元素的背景颜色?

时间:2016-10-13 08:39:46

标签: javascript jquery html css background-color

想就此问题寻求帮助。我用2种背景颜色(红色和绿色)制作了4个盒子而不使用html。

这是我的jsfiddle:https://jsfiddle.net/2bk1Ldg2/3/

如何确定现有的背景颜色css,以便在5秒内交替更改(红色到绿色,绿色到红色)。

不知道搜索此类问题的最佳查询是什么。你真棒的答案对我的学习有很大的帮助。非常感谢!

$(document).ready(function() {
function() {
    $( ".div1, .div3" ).animate({backgroundColor: 'red'
  }, 5000)};
});

1 个答案:

答案 0 :(得分:1)

您应该使用setInterval()重复代码几秒钟。由于您在background属性中添加了style元素,因此您可以使用HTMLElement.style获取名称背景颜色。

setInterval(function(){  
    $("div").each(function(){
        this.style.background = this.style.background == "green" ? "red" : "green";
    });
}, 5000);



setInterval(function(){  
  $("div").each(function(){
    this.style.background = this.style.background == "green" ? "red" : "green";
  });
}, 1000);

div { height: 50px }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background: green"></div>
<div style="background: red"></div>
<div style="background: green"></div>
<div style="background: red"></div>
&#13;
&#13;
&#13;

相关问题