【发布时间】:2021-02-11 16:24:14
【问题描述】:
我有一个默认背景颜色(黑色)的按钮。将鼠标悬停在此按钮上时,我想更改此按钮的背景颜色(来自数组)。我让它在基本层面上工作,但我希望它一遍又一遍地重复循环。 这就是我目前所拥有的。
var color = ['#3e50a2', '#faa51a', '#ed1c24', '#2a9446'];
var i = -1;
document.querySelector('.customBtn').addEventListener('mouseover', function() {
i = 1 < color.length ? ++i : 0;
document.querySelector('.customBtn').style.background = color[i]
});
document.querySelector('.customBtn').addEventListener('mouseout', function() {
document.querySelector('.customBtn').style.background = '#000';
})
<a class="customBtn">Button</a>
【问题讨论】:
-
使用
setInterval? -
你没有改变
color的内容,那么i = 1 < color.length ? ++i : 0;除了在每个mouseover事件上不断增加i之外应该做什么? -
应该是
i < color.length(这就是我的意思:-) -
为什么不为此使用 CSS 动画?
-
您可能需要考虑使用Iterate an array infinite times with for each and setTimeout 的答案中概述的方法
标签: javascript html