简体   繁体   English

为什么CSS过渡在页面加载时不起作用?

[英]Why don't CSS transitions work on page load?

It seems that changing CSS properties with JavaScript doesn't work with transitions when executing the JavaScript code on page load. 似乎在页面加载时执行JavaScript代码时,使用JavaScript更改CSS属性不适用于过渡。

Here is an example: 这是一个例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Test</title>
  <style>
    div {
      background: red;
      width: 300px;
      height: 300px;
      transition: 0.5s;
    }
  </style>
</head>
<body>
  <div />
  <script>
    var div = document.querySelector("div");

    // the following doesn't work as intended
    div.style.marginTop = "100px";

    // the following works fine
    /*setTimeout(() => (
    div.style.marginTop = "100px"
    ), 0);*/
  </script>
</body>
</html>

This can be resolved by encapsulating the changes to be made in a call to setTimeout() , even with 0 as second argument. 这可以通过封装对setTimeout()的调用中要进行的更改来解决,即使第二个参数为0

Can someone explain me this behaviour? 有人可以向我解释这种行为吗?

The JavaScript code is run before the first frame. JavaScript代码在第一帧之前运行。 And because the first frame being rendered already has the changed values no transition is starting. 并且由于要渲染的第一帧已经具有更改的值,因此没有过渡开始。

setTimeout(...,0) works because setTimeout creates a callback and waits until the main thread is free, which is after the rendering process. setTimeout(...,0)之所以起作用,是因为setTimeout创建了一个回调并等待直到主线程空闲为止,这在渲染过程之后。

Wrapping your JS in a window.onload function which it is fired after the entire page loads, including its content (images, css, scripts, etc...) will fix this. 将JS包装在window.onload函数中,可以在整个页面加载触发JS,包括其内容(图像,css,脚本等),可以解决此问题。

 window.onload = function () { var div = document.querySelector("div"); // the following doesn't use the transition div.style.marginTop = "100px"; // the following uses the transition /*setTimeout(() => ( div.style.marginTop = "100px" ), 0);*/ }; 
 div { background: red; width: 300px; height: 300px; transition: 1s; } 
 <div /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM