javascript - 单击,触发动画和播放声音。从 keydown 到单击
问题描述
遵循这个架子鼓教程,但想将其更改为我可以单击而不是按键的位置(在此示例中,按 A 会触发动画和声音)。尝试将 window.addEventListener 中的“keydown”更改为“click”,但没有任何反应。我究竟做错了什么?
如果需要,请提供更多详细信息。有两个功能。第一个播放与 data-key div 的 keycode 匹配的相应音频标签。第二个函数只是将 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 元素上。例如可以使用相同的forEach循环
keys.forEach((key) => {
key.addEventListener('transitionend', removeTransition);
key.addEventListener('click', playSound);
});
推荐阅读
- html - 悬停时翻译 css 时按钮文本模糊
- node.js - 智能合约:.methods.request().send() 不显示任何内容
- elasticsearch - Elasticsearch Kubernetes pod - 无法连接到端口 9300
- javascript - ReferenceError: $ is not defined - 它曾经工作正常,但现在它坏了 - Rails 5
- javascript - 如何防止在可放置 div 之外拖动(移动)元素?(仅限 Vanila JS)
- python - 如何在 Python 中每 2 秒调用一次函数?
- php - 仅从一个文件中删除 .php 扩展名以与 Laravel 路由器一起使用
- windows - 如何使用 dir 命令仅显示不带扩展名的文件名
- python - AttributeError: 'Turtle' 对象没有属性 'addshape'
- python - 在python中更改数组的某些索引的值