hello~
今天咱来学习一个音效按钮的小Demo!!!
按钮音效
Part 1
HTML结构
<body>
<audio id="applause" src="sounds/applause.mp3"></audio>
<audio id="boo" src="sounds/boo.mp3"></audio>
<audio id="gasp" src="sounds/gasp.mp3"></audio>
<audio id="tada" src="sounds/tada.mp3"></audio>
<audio id="victory" src="sounds/victory.mp3"></audio>
<audio id="wrong" src="sounds/wrong.mp3"></audio>
<div id="buttons"></div>
</body>
Part 2
<style>
* {
box-sizing: border-box;
}
body {
background-color: rgb(161, 100, 223);
font-family: 'Poppins', sans-serif;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
text-align: center;
height: 100vh;
overflow: hidden;
margin: 0;
}
.btn {
background-color: rebeccapurple;
border-radius: 5px;
border: none;
color: #fff;
margin: 1rem;
padding: 1.5rem 3rem;
font-size: 1.2rem;
font-family: inherit;
cursor: pointer;
transition: all .3s;
}
.btn:hover {
opacity: 0.9;
transform: translateY(-5px);
box-shadow: 3px 2px 2px #2a2a2a;
border: rgb(161, 100, 223);
}
.btn:focus {
outline: none;
}
</style>
Part 3
<script>
const sounds = ['applause', 'boo', 'gasp', 'tada', 'victory', 'wrong']
// forEach 遍历 sounds 里的每一个元素
sounds.forEach(sound => {
const btn = document.createElement('button')
btn.classList.add('btn')
btn.innerText = sound
document.getElementById('buttons').appendChild(btn)
btn.addEventListener('click', () => {
// 点击下一次 button 的时候 停止前一次未播完的音效
stopSongs()
document.getElementById(sound).play()
})
})
function stopSongs() {
sounds.forEach(sound => {
// 这里的每个 audio 标签里的 id 名是和 其数组元素名是一样的
const song = document.getElementById(sound)
song.pause()
})
}
</script>