在你的代码中,长按A键后再次按下A键确实没有触发效果。这是因为在playSound函数中,只有按下键盘的事件会触发添加playing类的操作,而不会检查是否已经存在playing类。因此,当你再次按下A键时,虽然代码执行了添加playing类的操作,但由于元素已经存在该类,所以没有触发过渡效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JS Drum Kit</title>
<link rel="stylesheet" href="style.css" />
<link rel="icon" href=" https://fav.farm/ ✅" />
<style>
body {
min-height: 100vh;
display: grid;
place-content: center;
}
#A {
width: 100px;
height: 100px;
color: white;
background: rgba(0, 0, 0, 0.4);
text-shadow: 0 0 0.5rem black;
border: 2px solid black;
display: grid;
place-content: center;
font-size: 2rem;
transition: all 0.07s ease;
}
.playing {
transform: scale(1.1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
</style>
</head>
<body>
<div data-key="A" id="A">A</div>
<script>
let timer
function removeTransition(e) {
console.log('transitionend', e)
if (e.propertyName !== 'transform') return
e.target.classList.remove('playing')
}
function playSound(e) {
console.log('key down')
if (e.code !== 'KeyA') return
elemA.classList.remove('playing')
setTimeout(() => {
elemA.classList.add('playing')
}, 10)
}
const elemA = document.querySelector('#A')
window.addEventListener('keydown', playSound)
window.addEventListener('keyup', () => {
console.log('key up')
clearInterval(timer)
})
elemA.addEventListener('transitionend', removeTransition)
</script>
</body>
</html>