<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #app { width: 200px; height: 200px; background-color: red; display: none; transition: all 1s; } </style> </head> <body> <div id="app"> </div> <button id="test">測試</button> </body> </html>
<style> #app { width: 200px; height: 200px; background-color: red; display: none; } </style> 。。。 <script> test.onclick = function () { const app = document.querySelector('#app') console.log(app, 'app') app.style.transform = "translateX(200px)" app.style.display = "block" } </script>
test.onclick = function () { const app = document.querySelector('#app') console.log(app, 'app') app.style.display = "block" const height = app.offsetHeight app.style.transform = "translateX(200px)" }
效果以下所示:
html
「過渡動畫」
是什麼狀況?display
是不能出現動畫的,因此標題+了引號
怎麼纔能有過渡?前端
0-1
.transition
裏面包含的屬性你們在寫現代前端框架,遇到最多的問題就是渲染的時期不肯定的問題。vue
vue
裏面的nextTick
實現,有一個優雅降級的實現。它在mounted
生命週期函數裏面去獲取dom
節點時候,常常獲取不到或者獲取不到完整渲染的dom
節點。(我好久沒有使用vue
了,有問題能夠補充),爲何?dom
節點按道理應該更新,但是更新時機是咱們沒法肯定的,由於這中間有中間層,好比存在diff
算法計算過程,可能存在隊列,由於當你頻繁修改數據的時候,框架自己要作優化,合併一段時間的數據更新再去真正更新dom
,等這些事情都作完了,才能去更新dom
節點,而後咱們才能看到最新數據對應的節點dom
節點的時候,也存在一個隊列。這個就是瀏覽器的渲染隊列
---git
React
系列文章中的setState
異步隊列實現何時最能體現這個隊列的做用?github
dom
時候,例如for
循環裏面頻繁操做dom
,這個時候瀏覽器就會優化咱們的操做,合併一部分操做一次性執行display
的關聯<script> test.onclick = function () { const app = document.querySelector('#app') console.log(app, 'app') app.style.display = "block" const height = app.offsetHeight app.style.transform = "translateX(200px)" } </script>
app.style.display = "block"
這行代碼時候,dom
節點此時並無更新,js
解析引擎是聰明的,它發現你後面立刻有代碼要修改dom
節點,會先存入隊列中集中一次性操做app.offsetHeight
這行代碼時候,發現咱們須要讀取dom
節點的屬性,瀏覽器懼怕如今隊列中沒有執行的操做會讓你讀取到不正確的值引起BUG
,因而就會清空渲染隊列而且執行,讓你拿到最精確/新的
值當你請求向瀏覽器請求一些 style
信息的時候,就會讓瀏覽器flush
隊列,好比:算法
offsetTop, offsetLeft, offsetWidth, offsetHeight
scrollTop/Left/Width/Height
clientTop/Left/Width/Height
width,height
flush
隊列,offsetHeight
屬性後,咱們清空了渲染隊列,那麼此時dom
從新渲染完成後,此時display
已是block
了。並且展現在界面上面了,咱們再操做dom
屬性就會出現過渡動畫了。https://github.com/JinJieTan/Peter-
,記得Star
哦
[前端巔峯]
若是感受對你有幫助,能夠點個贊
/在看
,讓更多人看到個人這篇文章