我的 .style.background 不设置项目的样式



我试图使一个计时器,使它,当时间得到低于10秒的文本变成红色。我使用backgornd -clip样式我的文本,但由于某种原因,我的js没有样式的背景元素,我想。

这是我的JavaScript:

if (miliseconds < 10 && seconds < 10)
document.getElementById("timer").textContent = `0${seconds}:0${miliseconds}`;
else if (miliseconds < 10)
document.getElementById("timer").textContent = `${seconds}:0${miliseconds}`;
else if (seconds < 10)
{
document.getElementById("timer").textContent = `0${seconds}:${miliseconds}`;
document.getElementById("timer-back-2").style.background = "repeating-linear-gradient(to left, red, red 5px, black 5px, black 6px);";
}
else 
{
document.getElementById("timer").textContent = `${seconds}:${miliseconds}`;
document.getElementById("timer-back-2").style.background = "repeating-linear-gradient(to left, blue, blue 5px, black 5px, black 6px);"
}
这是我的CSS:
#timer-back-2{
width: 100%;
height: 100%;
margin: 0;
background: repeating-linear-gradient(to left, yellow, yellow 5px, black 5px, black 6px);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
#timer{
width: 100%;
height: 100%;
margin: 0;
background: repeating-linear-gradient(to top, transparent, transparent 5px, black 5px, black 6px);
z-index: 3;
font-size: 50px;
font-family: "8-bit-operator";
display: flex;
justify-content: center;
align-items: center;
-webkit-background-clip: text;
background-clip: text;
}

不要尝试在javascript中切换属性值,而是使用类。使用background-image代替backgroundrepeating-linear-gradient(),否则从其他类的背景属性可能会覆盖其他背景属性已经设置。

const timer = document.getElementById('timer-back-2');
// turn it red
timer.classList.add("red");
// turn it blue    
timer.classList.remove("red");
timer.classList.add("blue");
// turn it yellow
timer.classList.remove("red");
timer.classList.remove("blue");
// demo changes color every second
window.setInterval(function() {
timer.classList.remove("blue");
timer.classList.remove("red");
const time = (new Date).getTime();
if (time % 2 == 0) {
timer.classList.add("red");
} else if (time % 3 == 0) {
timer.classList.add("blue");
}
}, 1000);
#timer-back-2 {
width: 100px;
height: 100px;
font-size: 32px;
background-image: repeating-linear-gradient(to left, yellow, yellow 5px, black 5px, black 6px);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
#timer-back-2.red {
background-image: repeating-linear-gradient(to left, red, red 5px, black 5px, black 6px);
}
#timer-back-2.blue {
background-image: repeating-linear-gradient(to left, blue, blue 5px, black 5px, black 6px);
}
<div id="timer-back-2">Back 2</div>

最新更新