<!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
哦[前端巅峰]
若是感受对你有帮助,能够点个赞
/在看
,让更多人看到个人这篇文章