Javascript播放并暂停一首歌曲,只需点击同一图像即可

时间:2013-03-23 12:33:58

标签: javascript html5 css3 dom

嗨我试着在我点击时暂停播放歌曲并暂停时再次点击它但是它似乎只是在播放这是下面的代码:

的Javascript

 function StartOrStop(audioFile)
  {
    var audie = document.getElementById("myAudio");
    if(!audie.src) 
       audie.src = audioFile;
    if(audie.paused == false)
     {
        audie.pause();
     }
     else
     {
       audie.play();
     }
  }

HTML5

<img src="images/play.png" alt="Play Button width="57" height="50" onclick="StartOrStop('RWY.mp3')" >

关于我如何解决它的任何建议?

1 个答案:

答案 0 :(得分:2)

当您点击image时,它会调用StartOrStop函数,这会再次导致src视频集,从而导致pausedtrue所以你不能暂停视频,只是再次播放。

此版本应该有效:

HTML:

<img src="images/play.png" alt="Play Button" width="57" height="50" onclick="StartOrStop('RWY.mp3')">

<audio id="myAudio"></audio>

使用Javascript:

function StartOrStop(audioFile) {
    var audie = document.getElementById("myAudio");
    if (!audie.src || audie.src !== audioFile) audie.src = audioFile; // check if there's a src already and if the current src is not the same with the new one, change it. Or don't do anything.
    if (audie.paused == false)
        audie.pause();
    else
        audie.play();
}

小提琴:http://jsfiddle.net/QCGYP/4/