简体   繁体   中英

Change background color on click and drag

I'm trying to create a website where the background color changes as you click and drag it. The problem is that the background color does update in my code, but it doesn't have that nice smooth consistently smooth gradient effect. It just jumps from color to color as you drag.

In this code the effect I want is achieved by the mousemove event listener:

 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>

According to this page you can't transition a background gradient using CSS. He provides a possible solution to achieve that effect with the help of a pseudo-element and an opacity transform instead.

 .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/ --

Add css transition if you want smooth color change:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM