如何給新添加的DOM節點加動畫效果
最近碰到項目中,在DOM節點中,添加新的
html
后 要有動畫效果,一直沒能很好地理解,嘗試了各種方式,終於找出來了
- 簡化版結構
代碼如下 使用jq1.9以上版本
css
.box {
padding: 10px;
background-color: #eee;
}
.dv {
margin-bottom: 10px;
width: 200px;
height: 150px;
background-color: skyblue;
}
.dv:nth-of-type(2n) {
background-color: pink;
}
.btn {
width: 120px;
height: 34px;
border-radius: 3px;
background-color: blue;
}
html
<div class="box">
<div class="dv"></div>
</div>
<div class="btn">按鈕</div>
js
$(function () {
const templete = `<div class="dv"></div>`
$('.btn').on('click', function () {
$('.box').append(templete)
$('.box').find('.dv:last-of-type').slideDown(100)
})
})
效果圖
結果一點動畫效果都沒有,對其父設置都無效,很是奇怪,明明已經找到這個元素卻依舊無法實現,只能想想其他方法,看看文檔,終於發現,執行動畫需要從無到有,而我也一直以為DOM添加的節點本來就是從無到有,實際上卻是 該DOM節點設置為
display: none
然后變為block
,這才是真正的從無到有,所以接着就迎刃而解了
css
.none {
display: none;
}
js
$(function () {
// 添加的 元素追加 none 默認不顯示
const templete = `<div class="dv none"></div>`
$('.btn').on('click', function () {
$('.box').append(templete)
$('.box').find('.dv:last-of-type').slideDown(100)
})
})
效果
總結
- 使用jquery時, 明明已經是 3以上的版本,使用
:last-of-tyoe
無法實現,而當前這個例子卻可以,實在是無語 - 動畫效果本來不難,但是卻沒想到花費我這么長時間,一直都沒想到是這個原因,終於找到了,記錄一筆,避免下次再采坑
這兩天在看vue時,也發現這樣的要求 單元素/組件的過渡
- 條件渲染 (使用 v-if)
- 條件展示 (使用 v-show)
- 動態組件
- 組件根節點
這篇文章
There are three classes to handle the A to B transition for when the element is displayed, and another three to handle the A to B transition for when the element is removed.
越理解原因,越好操作,加油