js模仿微信语音播放的小功能

自己写的一个模仿微信语音播放的小功能,实现的主要功能是:点击播放,点击暂停,播放切换,,,  代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    li {
      list-style: none;
      width: 100px;
      height: 30px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
    }
    .voice_play {
      display: none;
    }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <ul>
    <li id="1" data-time="5">
      <audio preload="auto" hidden="true"><source src="./明智之举.mp3" type="audio/mpeg"></audio>
      <img src="./i_voice_other.png" alt="" class="voice_stop">
      <img src="./i_voice_other.gif" alt="" class="voice_play">
    </li>
    <li id="2" data-time="10">
      <audio preload="auto" hidden="true"><source src="./tik_tok.mp3" type="audio/mpeg"></audio>
      <img src="./i_voice_other.png" alt="" class="voice_stop">
      <img src="./i_voice_other.gif" alt="" class="voice_play">
    </li>
    <li id="3" data-time="14">
      <audio preload="auto" hidden="true"><source src="./You&I.mp3" type="audio/mpeg"></audio>
      <img src="./i_voice_other.png" alt="" class="voice_stop">
      <img src="./i_voice_other.gif" alt="" class="voice_play">
    </li>
  </ul>
</body>
<script>
  // 展示语音播放和暂停是通过两张图片切换,一张静态图,一张GIF动图,这里就不传图片,下载的时候自己放入图片即可
  // 语音的时长这里是模拟的,一般是后台会返回,根据实际时长取
$('li').click(function () { var val = $(this).attr('val') // 每次点击前清除定时器 clearTimeout(timeId) var audio = $(this).children("audio")[0] // 语音的时长 var time = $(this).data('time') // console.log(time) // 判断当前点击的是否已经在播放, value的值是自己设置的用来区分播放状态和暂停状态的,1是未播放状态,2是已经在播放状态 if (val && val == 2) { // console.log('if') $(this).children('.voice_play').hide() $(this).children('.voice_stop').show() audio.pause() // 暂停 // 重新设置为空,方便下一次点击 $(this).attr('val', 1) } else { // console.log('else') // 找到除点击之外的其他语音,判断这次点击之前是否已经有歌曲在播放,如果是从其他的语音跳转过来, // 要把以前播放的状态改变,,总体思路:页面上只能有一个语音在播放,只有一个val为2 $('li').attr('val', 1) $(this).attr('val', 2)
var audiolist = $('li').children("audio") // 暂停其他播放 for (let i = 0; i < audiolist.length; i++) { // console.log(audiolist[i]) audiolist[i].pause() } $('li').children('.voice_play').hide() $('li').children('.voice_stop').show() $(this).children('.voice_play').show() $(this).children('.voice_stop').hide() audio.load() //加载 audio.play() //播放 } // console.log($('li').children("audio")) // 语音播放完切换动画 var timeId = setTimeout(() => { // console.log('set',time) $(this).children('.voice_play').hide() $(this).children('.voice_stop').show() $(this).attr('val', 1) }, time * 1000) }) </script> </html>

 

posted @ 2018-08-08 16:29  潇湘羽西  阅读(1009)  评论(0编辑  收藏  举报