Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - CSS-filter transition

my query is : Whenever I press any button for the first time, the image successfully transitions to the desired filter in 4 seconds. But when I press another button the transition takes place immidiately without 4 seconds. How do I make the picture change in 4 seconds everytime I press the buttons?.

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To be able to transition from one filter to an other, you need to have the same <filter_function> list inside your style declaration between the states.

It seems that otherwise browsers won't do the transition, even if you force to come back 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...