我正在尝试创建一个网站,当您单击并拖动它时,背景颜色会发生变化。问题是背景颜色在我的代码中确实会更新,但它没有那种漂亮的平滑始终如一的平滑渐变效果。当您拖动时,它只是从一个颜色跳到另一个颜色。
在此代码中,我想要的效果是通过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>
根据此页面,您无法使用 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/ --
如果要平滑更改颜色,请添加csstransition
:
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>