单击并更改背景颜色

时间:2020-01-17 20:03:54

标签: javascript css dom css-transitions

我正在尝试创建一个网站,您单击并拖动该网站时背景颜色会发生变化。问题是背景颜色确实会在我的代码中更新,但没有很好的平滑一致平滑效果。拖动时,它会从一种颜色跳到另一种颜色。

在这段代码中,我想要的效果是通过mousemove事件监听器实现的:

document.addEventListener('mousemove', function(event) {
  var width = window.innerWidth / 255
  var height = window.innerHeight / 255
  var xValue = event.clientX / width;
  var yValue = event.clientY / height;
  document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
});
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: white;
  height: 100vh;
  width: 100%;
}
<body id="bg">
  <div></div>
</body>

2 个答案:

答案 0 :(得分:1)

根据此page,您无法使用CSS转换背景渐变。他提供了一种可能的解决方案,可借助伪元素和不透明度转换来实现该效果。

.gradient {
  position: relative;
  background-image: linear-gradient(
    to right,
    hsl(211, 100%, 50%),
    hsl(179, 100%, 30%)
  );
  z-index: 1;
  height: 100px;
}

.gradient::before {
  position: absolute;
  content: "";
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(
    to bottom,
    hsl(344, 100%, 50%),
    hsl(31, 100%, 40%)
  );
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}

.gradient:hover::before {
  opacity: 1;
}
<div class="gradient"><a href="#">test to verify content remains visible & on top</a></div>
Hover over the element above to fade the background gradient.

<!-- Full write-up at http://keithjgrant.com/posts/2017/07/transitioning-gradients/ --

答案 1 :(得分:1)

如果要平滑的颜色更改,请添加css transition

document.addEventListener('click', function(event) {
  var xValue = Math.floor(Math.random() * 256);
  var yValue = Math.floor(Math.random() * 256);
  document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
});
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: white;
  transition: 500ms background;
  height: 100vh;
  width: 100%;
}
<body id="bg">
  <div></div>
</body>