HTML + CSS + JavaScript 实战小项目 【播放音效盒】

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>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值