Css transition is not a trigger, adding classes to the same function

when i click on the window the CSS transition is not a 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>
Run codeHide result

then I modify the script, use setTimeoutto add a 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>
Run codeHide result

so I think that the period of time between changing CSS properties can cause CSS transition?

so I add time between class additions. It also does 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 of classes in the same function cannot cause css transition?

+4
source share
3 answers

If we delve deeper into the V8 JavaScript engine, execution may be broken, which may clarify the current behavior. JavaScript is single-threaded, more precisely

== ==

enter image description here

, setTimeout WebAPI, . WebAPI , "", JavaScript.

. : classList , "

"Render Queue", V8, :

enter image description here

"". , , " ", , WebAPI. , , script setTimeout, .

https://youtu.be/8aGhZQkoFbQ

+2

div ( - 0).

const div = document.querySelector('div');
window.onclick = function() {
  div.classList.add('fade');
  div.classList.add('in');
}
div {
  opacity: 0;
  transition: opacity 2s linear;
}

.fade {}

.fade.in {
  opacity: 1;
}
<div>aaaa</div>
Hide result
0

, . 1, .fade.in 1, .

: classList , .

"in" , .fade 0. , 0 1, .

0
source

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


All Articles