transitionend 事件在 CSS transition 结束後觸發。
當 transition 完成前移除 transition 時,比如移除 css的transition-property 属性,事件不會被觸發
如在 transition 完成前設置 display: none ,事件同样不会被触发。
link
利用transitionend事件,監聽所有 block 上有 transition 的 CSS 屬性,並且透過 propertyName 來判斷是哪個 css 屬性
<div class="keys">
<button class="key" data-key="65">
<span class="letter">A</span>
<span class="sound">clap</span>
</button>
<button class="key" data-key="83">
<span class="letter">S</span>
<span class="sound">hihat</span>
</button>
</div>
.key {
border: .3rem solid rgb(53, 53, 53);
border-radius: .5rem;
margin: 1rem;
font-size: 1.5rem;
padding: 1rem .5rem;
transition: all .07s ease;
width: 10rem;
text-align: center;
color: white;
background: rgba(0,0,0,0.4);
text-shadow: 0 0 .5rem black;
}
// querySelectorAll 抓出 所有含有 .key 的數值
const keys = document.querySelectorAll('.key')
console.log('keys', keys)
// keys NodeList(2)
keys.forEach(item => {
console.log('item', item)
})
keys.forEach(item => {
item.addEventListener('transitionend', function(e){
console.log('trans', e)
})
})
原教學是利用監聽 transitionend ,然後找到 propertyName 裡面的 transform
判斷如果不是 transform 的時候跳出
如果是的時候移除 playing 這個 class
案件點擊 console.log(this) 會得到
這邊與第二點不一樣的地方是,沒有 propertyName 判斷,直接在 target 抓到這個元素直接取消他的 classList
目前不知道,與第二點教學的差別,但還是成功的狀態
// css style
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`)
key.classList.add('playing')
const keys = document.querySelectorAll('.key')
// 利用 forEach 方法讀取 NodeList 並為每一個元素監聽 transitionend 事件
keys.forEach(item => {
item.addEventListener('transitionend', function(e){
console.log('ssss',e.target)
e.target.classList.remove('playing')
})
})
JS