# CSS transition 後觸發transitionend 事件 <div class="block"> 監聽每一個按鍵是否有 transitionend 事件 </div> ## 觸發時機 > transitionend 事件在 CSS transition 结束後觸發。 > > 當 transition 完成前移除 transition 時,比如移除 css的transition-property 属性,事件不會被觸發 > > 如在 transition 完成前設置 display: none ,事件同样不会被触发。 > [link](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/transitionend_event) ## 監聽有 transition 的 CSS 屬性 利用transitionend事件,監聽所有 block 上有 transition 的 CSS 屬性,並且透過 propertyName 來判斷是哪個 css 屬性 ### 範例: 1. html: 假設 keys 裡面有兩組包起來的 button ```htmlmixed= <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> ``` css: 其中 class key 有 transition ```css= .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; } ``` javascript: ```javascript= // querySelectorAll 抓出 所有含有 .key 的數值 const keys = document.querySelectorAll('.key') console.log('keys', keys) // keys NodeList(2) ``` 2. 利用 forEach 方法讀取 NodeList 並為每一個元素加上 transitionend 事件 ```javascript= keys.forEach(item => { console.log('item', item) }) ```  ```javascript= keys.forEach(item => { item.addEventListener('transitionend', function(e){ console.log('trans', e) }) }) ```  觀察 propertyName 判斷是哪個屬性,找到 transform > 原教學是利用監聽 transitionend ,然後找到 propertyName 裡面的 transform > > 判斷如果不是 transform 的時候跳出 > > 如果是的時候移除 playing 這個 class  案件點擊 console.log(this) 會得到  這邊的 this 就是監聽的 key 3. 完整:增加 class playing ,然後監聽變化並移除 > 這邊與第二點不一樣的地方是,沒有 propertyName 判斷,直接在 target 抓到這個元素直接取消他的 classList > > 目前不知道,與第二點教學的差別,但還是成功的狀態 ```javascript= // 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') }) }) ``` <iframe height="300" style="width: 100%;" scrolling="no" title="Untitled" src="https://codepen.io/unayo/embed/BawQVeO?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/unayo/pen/BawQVeO"> Untitled</a> by unayo (<a href="https://codepen.io/unayo">@unayo</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ###### tags: `JS` {%hackmd @unayojanni/H1Qq0uKkK %}
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up