Further practice on automatic background changes with JavaScript and CSS
P粉875565683
2023-08-15 16:52:20
<p>In my previous question, with the help of (Jan) I solved the problem of automatic background change. </p>
<p>My previous question: Automatic background changes using JavaScript and CSS</p>
<p>But when the background changes, the jump in color is visible, and I want the color change to be seamless and slow. </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">var i = 0;
function changeBackgroundColor() {
var background = document.getElementById("background");
if (i % 2 === 0) {
background.classList.remove("background-body");
} else {
background.classList.add("background-body");
}
i = i 1;
}
setInterval(changeBackgroundColor, 3 * 1000);</pre>
<pre class="brush:css;toolbar:false;">html,body{
width: 100%;
overflow-x: hidden !important;
height: 100%;
overflow-y: hidden !important;
}
#background{
width: 100%;
height: 100%;
background: #39c787;
background-image: -webkit-gradient(linear, 15% 0%, 75% 84%, from(#ca83ddc4), to(#7874e3f3), color-stop(70%, #dfa450ab));
transition: all 5s ease;
-webkit-transition: all 5s ease;
-moz-transition: all 5s ease;
-o-transition: all 5s ease;
-ms-transition: all 5s ease;
}
.background-body{
background: #e0922d !important;
background-image: -webkit-gradient(linear, 15% 0%, 75% 84%, from(#9283ddc4), to(#22ff12d1), color-stop(70%, #c550dfab)) !important;
transition: all 5s ease;
-webkit-transition: all 5s ease;
-moz-transition: all 5s ease;
-o-transition: all 5s ease;
-ms-transition: all 5s ease;
}</pre>
<pre class="brush:html;toolbar:false;"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> ;</script>
<body id="background"></body></pre>
<p><br /></p>
To make the background color change smoothly, you need to add the transition attribute to the background-color attribute. The following code can achieve this effect:
Use an absolutely positioned pseudo-element with a different background, and then make an opacity change transition on top of it.