随着时间的推移获得 CSS 个值
getting CSS values over time
我正在尝试获取某个元素以前和当前的颜色,但不知道该怎么做。任何建议将不胜感激!
我不确定这个问题是要求只记住当前和以前的颜色,还是要求一直记住它们。
假设它是第一个,此代码段只是添加一行以将当前颜色保存在另一个数据属性 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>
我正在尝试获取某个元素以前和当前的颜色,但不知道该怎么做。任何建议将不胜感激!
我不确定这个问题是要求只记住当前和以前的颜色,还是要求一直记住它们。
假设它是第一个,此代码段只是添加一行以将当前颜色保存在另一个数据属性 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>