簡體   English   中英

為什么CSS過渡在頁面加載時不起作用?

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

似乎在頁面加載時執行JavaScript代碼時,使用JavaScript更改CSS屬性不適用於過渡。

這是一個例子:

<!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>

這可以通過封裝對setTimeout()的調用中要進行的更改來解決,即使第二個參數為0

有人可以向我解釋這種行為嗎?

JavaScript代碼在第一幀之前運行。 並且由於要渲染的第一幀已經具有更改的值,因此沒有過渡開始。

setTimeout(...,0)之所以起作用,是因為setTimeout創建了一個回調並等待直到主線程空閑為止,這在渲染過程之后。

將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