点击,触发动画和播放声音.从键向下到单击



按照这个鼓组教程,但想将其更改为我可以单击而不是按键的位置(在本例中按 A 会触发动画和声音(。尝试将 window.addEventListener 中的"键下"更改为"单击",但没有任何反应。我做错了什么?

如果需要,可提供额外的详细信息。有两个功能。第一个播放与数据键div 的键码匹配的相应音频标签。 第二个函数只是将 css 中的转换返回到其原始状态。

function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
if (!audio) return; //stop the function from running all together
audio.currentTime = 0; // rewind to the start
audio.play();
key.classList.add('playing');
}
function removeTransition(e) {
if (e.propertyName !== 'transform') return; // skip it if its not a transform
this.classList.remove('playing');
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener('keydown', playSound);
@charset "UTF-8";
/* CSS Document */
html {
font-size: 10px;
/*background: url(http://i.imgur.com/b9r5sEL.jpg) bottom center;*/
/* background-size: cover;*/
}
body,
html {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.keys {
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
justify-content: center;
}
.key {
border: .4rem solid mistyrose;
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(245, 245, 220, 0.4);
text-shadow: 0 0 .5rem black;
}
.playing {
transform: scale(1.1);
border-color: black;
box-shadow: 0 0 1rem black;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Drum Kit</title>
<link rel="stylesheet" href="soundpad.css">
</head>
<body>
<div class="keys">
<div data-key="65" class="key">      
</div>
</div>
<audio data-key="65" src="clap.wav"></audio>

</body>
</html>

您遇到的问题归结为您试图用来获取数据的错误属性。 当您按下键盘上的按钮时,可以使用keyCode属性,但您的目标是从data-key属性中获取它。 所以首先你必须改变:

e.keyCode

e.target.dataset.key

喜欢这个:

const audio = document.querySelector(`audio[data-key="${e.target.dataset.key}"]`);
const key = document.querySelector(`.key[data-key="${e.target.dataset.key}"]`);

另外,您需要添加不是在窗口对象上而是在某些html元素上单击的侦听器。例如,可以用于每个循环

keys.forEach((key) => {
key.addEventListener('transitionend', removeTransition);
key.addEventListener('click', playSound);
});

最新更新