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

标签 javascript jquery html css background-color

<分区>

想就此寻求帮助。我在没有使用 html 的情况下制作了 4 个具有 2 种背景颜色(红色和绿色)的盒子。

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

我怎样才能找到一种方法来识别现有的背景颜色 css 以在 5 秒内交替更改它(红色到绿色和绿色到红色)。

不知道搜索此类问题的最佳查询是什么。您精彩的回答对我的学习帮助很大。非常感谢!

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

最佳答案

你应该使用 setInterval()重复您的代码几秒钟。因为你在 style 属性中添加了 background 元素,你可以使用 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>

关于javascript - 如何使用 jquery 每 5 秒更改元素的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016144/

相关文章:

javascript - arguments 对象在 ES6 中应该是可迭代的吗?

javascript - toDataURL() 小屏幕,保存的图像小

jquery - 点击悬停菜单中的链接

javascript - 来自 Controller .NET MVC 的模态弹出窗口

Javascript灯箱未捕获类型错误: $ is not a function

php - 似乎无法让 PHP 在 MAMP 中工作

javascript - 调用 angular.extend 不会导致 $scope.$watch 触发

javascript - 如何制作一个可以将任何看起来像 javascript 代码的字符串转换为对象的函数?

javascript - 动态表 onchange 和 td id

html - 在两行中显示 li 元素标题,以适应最大宽度