gpt4 book ai didi

javascript - 如何更改鼠标悬停和鼠标悬停时的动画颜色?

转载 作者:行者123 更新时间:2023-12-03 01:30:08 25 4
gpt4 key购买 nike

我正在构建一个主题切换器,因此当您将鼠标悬停在某物上时,它会改变颜色。

它有效。

现在,我想给它添加动画,我该怎么做?

我知道我需要一个可以做到这一点的函数,但不确定如何开始使用它。

这是 CodePen:https://codepen.io/Aurelian/pen/djYLxx?editors=0010

这是 HTML:

<div class="organic-body" data-color="#1f2f1e" style="background-color: rgb(31, 51, 34);">
<div class="container">

<h5>Hover to change color</h5>

<div class="organic-list">
<a href="#" class="organic-card js-organic-card-hover" data-color="red">
<h2>Color red</h2>
</a>

<a href="#" class="organic-card js-organic-card-hover" data-color="blue">
<h2>Color blue</h2>
</a>

<a href="#" class="organic-card js-organic-card-hover" data-color="green">
<h2>Color green</h2>
</a>
</div>

</div>
</div>

这是 JS:

document.addEventListener('DOMContentLoaded', function () {

// Select each item
var organicBody = document.querySelector(".organic-body"),
organicList = document.querySelector(".organic-list"),
organicCard = document.querySelectorAll(".organic-card");

organicCard.forEach(function(item) {
item.addEventListener('mouseover', function(event) {
var itemDataColor = item.getAttribute('data-color');
organicBody.style.backgroundColor = itemDataColor;

})
item.addEventListener('mouseout', function(event) {
var bodyColor = organicBody.getAttribute('data-color');
organicBody.style.backgroundColor = bodyColor;
});
})


// Set interval on how long you want it to animate
// Convert color to RGB

function animateColorChange() {

setTimeout(function(){

}, 3000);

}

});

最佳答案

只需修改 CSS 以包含 transition 属性,如下所示:

.organic-body {
height: 100vh;
transition: background-color 1000ms;
}

这意味着只要 background-color 属性发生变化,它应该在 1000 毫秒内逐渐过渡

编辑

如果你确实必须使用 JS(我强烈建议不要这样做),这大致就是你需要做的

let frames = 60; // The number of frames. The lower the number, the choppier the transition
let duration = 1000; // How long the transition should take
let from = [255, 0, 0]; // RGB values
let to = [0, 0, 255]; // RGB values

// Calculate the differences between the two
let diff = to.map((v, idx) => v - from[idx]);
// Divide that by the number of frames to find out what change should be made in each frame
let frameChange = diff.map(v => v / frames);

let elem = document.getElementById('example');
let step = 1;


function tick() {
from = from.map((v, idx) => v + frameChange[idx]);
elem.style.backgroundColor = `rgb(${from[0]}, ${from[1]}, ${from[2]})`;
step++;
if (step <= frames) {
setTimeout(tick, duration / frames)
}
}

tick()
div#example {
width: 100px;
height: 100px;
background-color: red;
}
<div id="example">
</div>

关于javascript - 如何更改鼠标悬停和鼠标悬停时的动画颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51341983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com