随着时间的推移获取 CSS 值

时间:2021-01-16 14:34:30

标签: html css attributes

我正在尝试获取元素的先前和当前颜色,但不知道该怎么做。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

我不确定是否要求只记住当前和以前的颜色,还是要求一直记住它们。

假设它是第一个,此代码段仅添加一行以在另一个数据属性 data-prev 中保存当前颜色,然后使用新颜色更新它。例如,我们可以确保此时不会两次选择相同的颜色。

该代码段将先前和当前的颜色写入控制台,以便我们检查它是否正常工作。

window.getRandomNumber = function (max) {
    return Math.floor(Math.random() * max)
}

var colors = ['red', 'blue', 'green', 'orange', 'purple'];
const changeHeadlineColor = function (croHeadline) {
    var random = getRandomNumber(5000);
    var randomString = random.toString();
    setTimeout(() => {
        var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0));
        croHeadline.setAttribute('data-prev', croHeadline.getAttribute('data-color')); //remember the current color
        croHeadline.setAttribute('data-color', colors[colorKey]);
        console.log(croHeadline.getAttribute('data-prev') + ' ' + croHeadline.getAttribute('data-color'));
        changeHeadlineColor(croHeadline);
    }, random);
};

changeHeadlineColor(document.querySelector('div'));
    [data-color="red"] { color: red; }
    [data-color="blue"] { color: blue; }
    [data-color="green"] { color: green; }
    [data-color="orange"] { color: orange; }
    [data-color="purple"] { color: purple; }
<div data-color="red">SOME TEXT</div>