javascript - 我的 .style.background 没有设置该项目的样式

我正在尝试制作一个计时器并使其在时间低于 10 秒时变为红色。我正在使用 backgorund-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;
}

回答1

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

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>

相似文章

html - 冻结 table 前两列

我有一个结构有点复杂的table,因为它有colspan和多个标题。我需要修复我的table前两列,其余列应该可以水平滚动。我尝试了各种示例来冻结列,但没有按预期工作。以下是我提到的链接。我希望在活动...

随机推荐

最新文章