如何在mouseon和mouseout上更改动画颜色?

时间:2018-07-14 17:51:47

标签: javascript javascript-events

我正在构建主题切换器,因此当您悬停某些内容时,它会更改颜色。

有效。

现在,我想向其中添加动画,该怎么办?

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

这是密码笔: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);

      }

});

1 个答案:

答案 0 :(得分:1)

只需将CSS修改为包含transition属性,就像这样:

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

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

编辑

如果您真的必须使用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>