原本許多需要js才能實現的動畫效果,通過CSS3就能輕易實現了,但是CSS3也有自身的不足,例如說在動畫觸發上就沒有js靈活,因此可以考慮將CSS3與Js結合使用。
一般使用transition過渡動畫都是利用css的狀態:hover,focus,active 來觸發,比如:
div{
width: 200px;
height: 200px;
background: #f00;
transition: height 2s,width 2s;
-moz-transition: height 2s,width 2s; /* Firefox 4 */
-webkit-transition: height 2s,width 2s; /* Safari and Chrome */
-o-transition: height 2s,width 2s; /* Opera */
}
div:hover{ /* 鼠標懸浮觸發 */
width: 400px;
height: 400px;
}
現在想通過js點擊事件來觸發CSS3的過渡動畫,可以在js中通過dom操作來改變div的css的具體屬性,如:
div{
display: none;
width: 200px;
height: 200px;
background: #f00;
transition: height 2s;
-moz-transition: height 2s; /* Firefox 4 */
-webkit-transition: height 2s; /* Safari and Chrome */
-o-transition: height 2s; /* Opera */
}
function clickMe() {
document.getElementsByTagName('div')[0].style.display = 'block';
setTimeout(() => {
document.getElementsByTagName('div')[0].style.height = '400px';
}, 100);
}
一個需要注意的地方:
當元素本身爲display:none
時,若此時我們想通過js先將其變爲display:block
並且隨後再觸發其他想要的transition過渡效果,需要在 js改變其爲display:block
後用setTimeout延遲100ms左右的時間再去設置其他過渡動畫,否則該過渡動畫不會觸發。