在同一函数中添加类不会触发css转换 [英] css transition is not trigger by add classes in a same function

查看:64
本文介绍了在同一函数中添加类不会触发css转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击窗口时,CSS转换不会触发。

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>

然后我更改脚本,使用 setTimeout 在中添加第二个类,它可以工作。

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>

所以我认为,是CSS之间的一段时间属性更改可以触发CSS转换吗?

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>

为什么更改同一函数中的类不能触发css转换?

why change classes in a same function can not trigger a css transition?

推荐答案

如果我们深入研究JavaScript V8引擎的工作,可以分解执行情况,这可以澄清当前的行为。 JavaScript是单线程的,更精确的是

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

如上所示,setTimeout是浏览器中的WebAPI的一部分。 WebAPIs的优先级低于作为核心JavaScript函数的堆栈方法。

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.

如上所述 这是至关重要的part:对元素的classList进行多次更改不会导致每次更改都重绘元素

原因是渲染队列是V8架构的功能部分,如下所示:

The reason for this is "Render Queue" which is functional part of V8 architecture as shown below:

渲染发生在'stack'方法执行之间。在所有堆栈都为空之后,将触发事件循环,并且它会提取传递给WebAPI的任何方法。这就是原因,在第二种情况下,当脚本更改为使用setTimeout时,它可以正常工作。

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.

更多详细解释可以在Philip Roberts博客上看到

More detailed explanation of this can be seen on Philip Roberts blog

https://youtu.be/8aGhZQkoFbQ

这篇关于在同一函数中添加类不会触发css转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆