我试图弄清楚如何通过空格键停止/恢复播放曲目。
我所有的按键都起作用了,只需要弄清楚如何在按下空格键时使其停止即可。
<div class="keys">
<div data-key="80" class="key">
<kbd>P</kbd>
<span class="sound">Sound 19</span>
</div>
<div data-key="32" class="stop">
<kbd>Spacebar</kbd>
<span class="sound">STOP</span>
</div>
</div>
<audio data-key="79" src="sounds/Sound18.wav"></audio>
<audio data-key="80" src="sounds/Sound19.wav"></audio>
<script>
function removeTransition(e) {
if (e.propertyName !== 'transform') return;
e.target.classList.remove('playing');
}
function playSound(e) {
const audio = document.querySelector(`audio[data-
key="${e.keyCode}"]`);
const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
if (!audio) return;
key.classList.add('playing');
audio.currentTime = 0;
audio.play();
}
const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key => key.addEventListener('transitionend',
removeTransition));
window.addEventListener('keydown', playSound);
</script>
关于如何解决此问题的任何想法?