when I click the window, CSS transition is not trigger.
const div = document.querySelector('div');
window.onclick = function() {
div.classList.add('fade');
div.classList.add('in');
}
.fade {
opacity: 0;
}
.fade.in {
transition: opacity 2s linear;
opacity: 1;
}
<div>aaaa</div>
then I change the script, use setTimeout
to add the second class in
, it works.
const div = document.querySelector('div');
window.onclick = function() {
div.classList.add('fade');
setTimeout(function() {
div.classList.add('in');
});
}
.fade {
opacity: 0;
}
.fade.in {
transition: opacity 2s linear;
opacity: 1;
}
<div>aaaa</div>
so I think, is nees a period time between CSS property change can trigger CSS transition?
so i add the time between add classes. it also not work.
<script>
window.onclick = function(){
div.classList.add('fade');
for(var i=0;i<10000; i++){
console.log(i);
}
div.classList.add('in');
}
</script>
why change classes in a same function can not trigger a css transition?
Triggering transitions You can trigger CSS transitions directly with pseudo classes like :hover (activates when the mouse goes over an element), :focus (activates when a user tabs onto an element, or when a user clicks into an input element), or :active (activates when user clicks on the element).
CSS transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time.
Transitioning two or more propertiesYou can transition two (or more) CSS properties by separating them with a comma in your transition or transition-property property. You can do the same with duration, timing-functions and delays as well. If the values are the same, you only need to specify one of them.
CSS3 Transition Properties Are Not Inherited (In AngularJS)
If we go deeper in working of JavaScript V8 engine, the execution could be broken down which could clarify the current behavior. JavaScript is single threaded, more precisely
one thread == one call stack == one thing at a time
As shown above setTimeout is part of WebAPIs which comes within browser. The priority of WebAPIs is lower than 'stack' methods which are core JavaScript functions.
As mentioned above "This is the crucial part: making multiple changes to an element's classList does not cause the element to be redrawn with each change"
The reason for this is "Render Queue" which is functional part of V8 architecture as shown below:
The rendering happens between the 'stack' method execution. After all the stack is empty 'event loop' is triggered and it pulls any method which was passed to WebAPIs. This is the reason, in second scenario when the script is changed to use setTimeout, it works.
More detailed explanation of this can be seen on Philip Roberts blog
https://youtu.be/8aGhZQkoFbQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With