我试图通过彩虹色循环改变链接的颜色。刷新时颜色应该与刚才相同,不要开始新的循环(因此CSS动画对我来说也没有用)。
我试图将此计算的颜色应用于链接的悬停功能。
var h = ( 60 * ( color[0] + time ) % 360 ) / 360;
materials[i].color.setHSL( h, color[1], color[2] );
var time = Date.now() * 0.00005;
任何帮助将不胜感激。
那样的东西?
var colors = [
'#FF0000', // Red
'#FF7F00', // Orange
'#FFFF00', // Yellow
'#00FF00', // Green
'#0000FF', // Blue
'#4B0082', // Indigo
'#9400D3', // Violet
];
var link = document.getElementById('link');
function calculateColor() {
var time = Math.floor(Date.now() / 1000);
link.style.color = colors[time % colors.length];
}
calculateColor();
setInterval(calculateColor, 100);
<p><a id="link" href="#">Link</a></p>
如果你需要另一个频率而不是1秒,你可以保持时间戳四舍五入到下一个时间间隔......我不知道我是否清楚自己,因为我不知道如何解释它。它是这样的:
var colors = [
'#FF0000', // Red
'#FF7F00', // Orange
'#FFFF00', // Yellow
'#00FF00', // Green
'#0000FF', // Blue
'#4B0082', // Indigo
'#9400D3', // Violet
];
var link = document.getElementById('link');
var freq = 5; // seconds
var time = Math.floor(Date.now() / 1000);
function calculateColor() {
var now = Math.floor(Date.now() / 1000);
var offset = now - time;
time = offset > freq ? now : time;
link.style.color = colors[time % colors.length];
}
calculateColor();
setInterval(calculateColor, 100);
<p><a id="link" href="#">Link</a></p>
这可以清理一下,但这应该让你开始。我假设色调是你实际想要保存的,因为你的方法是使用color [0]进行计算。所以我正在保存色调,但你可以修改它以满足你的需要。它使用网络存储来保存色调:https://www.w3schools.com/html/html5_webstorage.asp
// init function(run on page load, either fresh or after refresh)
$(function() {
var hue = null;
// check if local storage supported
if (typeof(Storage) !== "undefined") {
// check if hue saved
if (sessionStorage.hue) {
hue = sessionStorage.hue;
}
}
// check if hue is still null, if so, it is a fresh page load
// or storage isn't supported and we need to calculate it
if (!hue) {
// call your hue function here
hue = getNewHue();
}
// save hue
saveHue(hue);
});
// run everytime the mouse hovers over your link
// you can convert this to an interval function like
// in Jordi's answer if you want
$('#colorlink').on('hover', function() {
// get a new hue
var hue = getNewHue();
// call your hue function here
saveHue(hue);
})
function saveHue(hue) {
// set hue on link
var hslText = "hsl(" + hue + "," + color[1] + "%," + color[2] + "%)";
$('#colorlink').css({ color = hslText });
// also saving this to update materials[i] as well
// not sure if you still need this
materials[i].color.setHSL(hue, color[1], color[2]);
// save hue to storage in case of refresh
sessionStorage.setItem('hue', hue);
}
function getNewHue() {
return (60 * (color[0] + time) % 360) / 360;
}