CSS Filter Transition

my query: Whenever I press any button for the first time, the image successfully goes to the desired filter in 4 seconds. But when I press another button, the transition occurs smoothly without 4 seconds. How to make an image change in 4 seconds every time I press a button ?.

function change_image() { document.getElementById("blur").style.filter = "sepia(1)"; } function change_image_2() { document.getElementById("blur").style.filter = "grayscale(100%)"; } function change_image_3() { document.getElementById("blur").style.filter = "blur(5px)"; } 
 #blur { transition-duration: 4s; } 
 <div id="blur"> <img src="http://placehold.it/300" alt="whatever" height="400" width="300"> </div> <br> <button class="btn btn-success" type="button" onclick="change_image()">Sepia</button> <button class="btn btn-success" type="button" onclick="change_image_2()">Grayscale</button> <button class="btn btn-success" type="button" onclick="change_image_3()">Blur</button> 
+6
source share
2 answers

To be able to switch from one filter to another, you need to have the same <filter_function> list in the style declaration between states.

Otherwise, it seems that browsers will not perform the transition, even if you force none to return to none ...

So the solution is to always declare all your <filter_functions> and just set their argument to 0 .

 function change_image() { document.getElementById("blur").style.filter = "sepia(1) grayscale(0%) blur(0px)"; } function change_image_2() { document.getElementById("blur").style.filter = "sepia(0) grayscale(100%) blur(0px)"; } function change_image_3() { document.getElementById("blur").style.filter = "sepia(0) grayscale(0%) blur(5px)"; } 
 #blur { transition: all 4s; } 
 <div id="blur"> <img src="http://placehold.it/300" alt="whatever" height="400" width="300"> </div> <br> <button class="btn btn-success" type="button" onclick="change_image()">Sepia</button> <button class="btn btn-success" type="button" onclick="change_image_2()">Grayscale</button> <button class="btn btn-success" type="button" onclick="change_image_3()">Blur</button> 

I have not fully verified the main reasons yet, but from a quick read of this , I would say that browsers will be able to use the correct interpolation number between the same filters, but will not be different.

Now, how can he work out the first transition none from one filter?
Another riddle ...

+3
source

For me, the problem is that your buttons cannot go from shades of gray (100%) to undefined state. you should try your code using three style options on each button, for example:

 function change_image() { document.getElementById("blur").style.filter = "sepia(1)"; document.getElementById("blur").style.filter = "grayscale(0%)"; document.getElementById("blur").style.filter = "blur(0px)"; } 

I hope to help.

0
source

Source: https://habr.com/ru/post/1268833/


All Articles