html部分:
代码语言:javascript复制 <div class="keys">
<div data-key="65" class="key">
<kbd>A</kbd>
<span class="sound">clap</span>
</div>
<div data-key="83" class="key">
<kbd>S</kbd>
<span class="sound">hihat</span>
</div>
<div data-key="68" class="key">
<kbd>D</kbd>
<span class="sound">kick</span>
</div>
<div data-key="70" class="key">
<kbd>F</kbd>
<span class="sound">openhat</span>
</div>
<div data-key="71" class="key">
<kbd>G</kbd>
<span class="sound">boom</span>
</div>
<div data-key="72" class="key">
<kbd>H</kbd>
<span class="sound">ride</span>
</div>
<div data-key="74" class="key">
<kbd>J</kbd>
<span class="sound">snare</span>
</div>
<div data-key="75" class="key">
<kbd>K</kbd>
<span class="sound">tom</span>
</div>
<div data-key="76" class="key">
<kbd>L</kbd>
<span class="sound">tink</span>
</div>
</div>
<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
<audio data-key="70" src="sounds/openhat.wav"></audio>
<audio data-key="71" src="sounds/boom.wav"></audio>
<audio data-key="72" src="sounds/ride.wav"></audio>
<audio data-key="74" src="sounds/snare.wav"></audio>
<audio data-key="75" src="sounds/tom.wav"></audio>
<audio data-key="76" src="sounds/tink.wav"></audio>
图片展示:
注意一下: div为动画,audio为声音.
css部分:
代码语言:javascript复制*{padding: 0px;margin: 0px;list-style: none;font-family: sans-serif;}
html{
font-size: 12px;
}
.keys
{
display: flex;
min-height: 100vh;
align-items: center;
justify-content: center;
flex: 1;
}
.key
{
border: 0.4rem solid black;
border-radius: .5rem;
font-size: 1.5rem;
padding: 1rem .5rem;
transition: all .07s ease;
text-align: center;
color: white;
width: 10rem;
background: rgba(0,0,0,0.4);
text-shadow: 0 0 .5rem black;
}
.playing
{
transform: scale(1.1);
border-color: #ffc600;
box-shadow: 0 0 1rem #FFC600;
}
kbd
{
display: block;
font-size: 4rem;
}
.sound
{
font-size: 1.2rem;
letter-spacing: .1rem;
color: #ffc600;
text-transform: uppercase;
}
图片描述:
注意一下这里:
我只说最难点:flex:1;代表太大了就缩小到占满整个body的部分(系统合理分配),太小了就扩大到合适到占满整个整个body的地步(系统合理分配).
js部分:
代码语言:javascript复制<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>
图片展示:
注意一下: 整块项目的代码逻辑: js核心逻辑: 当窗口察觉到了你按下了有上面图片中的某一个键时,就playing(动画)起来,并且音乐从0开始播放。当playing与play():(声音)也就是动画结束之后,就移除动画. 注意一下: 要用什么得先获取 第二;先判断是否有这种东西
代码语言:javascript复制if (!audio) return;
第三:说
代码语言:javascript复制 `if(e.propertyName!=="transform")return;`
这里还没有发生你说还要做什么??是吧。