如何在“圆圈”内循环显示颜色?

问题描述 投票:0回答:4

我是编码新手,如何将颜色更改为“ bg-circle”。

我想让var“颜色”中的颜色通过“圆”。我已经尝试过,但逻辑不正确。

Javascript

var colors = ["blue", "red", "blue"]

HTML:

<div class="bg-circle">
    <div class="sm-circle"> 

    </div>          
</div>

CSS:

bg-circle{
width:40px;
height:40px;
border-radius:50%;
background:#ff7675;
}
javascript css arrays dom
4个回答
0
投票

也许这就是您要实现的目标:

const colors = ["blue", "red", "green"]
let currentColorIndex = 0;
//change color each second
setInterval(changeColor, 1000);

function changeColor() {
  document.querySelector('.bg-circle').style.backgroundColor = colors[currentColorIndex];
  currentColorIndex++;
  if(currentColorIndex == colors.length) {
    currentColorIndex = 0;
  }
}
.bg-circle{
width:40px;
height:40px;
border-radius:50%;
background:#ff7675;
}
<div class="bg-circle">
    <div class="sm-circle">
    </div>          
</div>

如果是这种情况,这里有一点解释:

使用setInterval方法,每隔XXXX毫秒执行一次函数,其中XXXX被设置为参数。有关它的更多信息here;

通过循环遍历colors数组,方法是保持当前活动索引为全局索引,并在超过颜色元素大小时将其重置。这样就可以旋转其元素。

[当您每秒获得正确的颜色(在我的情况下,我将间隔设置为每秒),您必须选择圆div。您可以使用querySelector完成此操作,该方法返回一个元素并直接设置其背景色属性。

我已经解决了CSS类样式的问题。您会在CSS代码中错过类名前面的点。


0
投票

您可以使用JavaScript来完成。

var colors = ["blue", "red", "blue"];
for(var i = 0; i < colors.length; i++) {
    document.getElementsByClassName('bg-circle')[0].style.backgroundColor = colors[i];
}

0
投票

您可以简单地使用setInterval进行此操作并循环抛出这些颜色。

var colors = ["blue", "red", "green"]

var smCircule = document.querySelector(".bg-circle");
var index=0;
setInterval(()=> {
smCircule.style.background = colors[index];
index++;
if (index>=colors.length)
    index=0;

},1000)
.bg-circle{
width:40px;
height:40px;
border-radius:50%;
background:#ff7675;
}
<div class="bg-circle">
    <div class="sm-circle"> 
    </div>          
</div>

0
投票

我在这里告诉您:“您可以在CSS中做到这一点。

.bg-circle{
    animation-name:toRed;
    animation-duration:2s;
    animation-iteration-count:infinite;
    animation-direction:alternate;
    background-color:blue;
    border-radius:25px;
    width:50px;
    height:50px;
}

@keyframes toRed{
    from{
      background-color:blue;
    }
    to{
        background-color:red;
    }
}
<div class="bg-circle"></div>

如果这是您想要的颜色之间的平滑变化。您还可以通过将关键帧的“从到”结构更改为0%,35%来使用多种颜色。 75%,100%。祝你有美好的一天。

© www.soinside.com 2019 - 2024. All rights reserved.