javascript - 每次刷新我的页面时,每个字母的颜色都是随机的

标签 javascript html css

每次刷新我的页面时,每个字母的颜色都是随机的。我怎样才能得到它以便有两种颜色,并且只是交替使用它们。

这是 HTML 颜色:

011a39 29c3fd

// Menu Visual
var myText = document.getElementById('myText');
var tempText = "";

for(let x in myText.textContent){
  var rnd =  Math.floor(Math.random() * (2 - 0 +  1));
  var rndBounce =  Math.floor(Math.random() * (11 - 5) + 5) / 10;
  if(rnd === 0){
    tempText += "<span style='color: #011a39; animation-duration: " + rndBounce + "s'>" + myText.textContent[x] + "</span>";
  } else if (rnd === 1) {
    tempText += "<span style='color: #29c3fd; animation-duration: " + rndBounce + "s'>" + myText.textContent[x] + "</span>";
  } else {
    tempText += "<span style='color: #011a39; animation-duration: " + rndBounce + "s'>" + myText.textContent[x] + "</span>";
  }
}
myText.innerHTML = tempText;
@keyframes bounce {
  from { top: 10px; }
  to { top: 0; }
}

#textContainer {
  position: absolute;
top: 100px;
    left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}

#myText {
  text-align: center;
}

#myText>span {
  position: relative;
  font-size: 5em;
  font-family: 'Baloo Bhaijaan', cursive; 
  animation-name: bounce;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
<div id="textContainer">
  <div id="myText">Hello</div>
</div>

最佳答案

我认为这对您有用。如果你想要其他颜色,只需在 colors 数组中更改它们

// Menu Visual
var myText = document.getElementById('myText');
var tempText = "";
var colors = ["#011a39", "#29c3fd"];
for(let x in myText.textContent){
var rndBounce =  Math.floor(Math.random() * (11 - 5) + 5) / 10;
    //you can use the modulus operator (%) to guarantee that the counter variable keeps alternating between 1 and 0 (the colors array length)
    tempText += "<span style='color: " + colors[x % 2] +"; animation-duration: " + rndBounce + "s'>" + myText.textContent[x] + "</span>";
}
myText.innerHTML = tempText;
@keyframes bounce {
  from { top: 10px; }
  to { top: 0; }
}

#textContainer {
  position: absolute;
top: 100px;
    left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}

#myText {
  text-align: center;
}

#myText>span {
  position: relative;
  font-size: 5em;
  font-family: 'Baloo Bhaijaan', cursive; 
  animation-name: bounce;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
<div id="textContainer">
  <div id="myText">Hello</div>
</div>

关于javascript - 每次刷新我的页面时,每个字母的颜色都是随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45926672/

相关文章:

javascript - nodejs 快速登录失败

python - 在 Python 中提取一些 HTML 标记值

html - 如何在 "flatten"iframe 中避免带有两个垂直滚动条的窗口

html - 将图像与文本垂直对齐

javascript - 选择要在表单中提交的字段

javascript - 从远程元素突出显示 Highcharts 系列

javascript - 如何在 Vue js 中使来自 localStorage 的数据具有反应性

html - 如何将 "Skip navigation"与 Durandal 路由器一起使用

javascript - 使用 Aurelia 对 Blur 进行现场验证

javascript - 幻灯片脚本下的子菜单元素