Play and Pause with onclick on the same Img

五迷三道 提交于 2020-01-06 21:13:28

问题


The following script is playing a soundfile when i click on a img (onclick). How do i pause it by clicking on the same img? I´ve tried audio.pause(), but it won´t work.

function play(){
var audio = document.getElementById("myaudio"); 
audio.style.display="block";
audio.play();
}

<a href="#" onclick="play()"><img src="Bilder/play2.png"></a>

回答1:


You should rename your function to audioHandler() for example which will handle whether to play or pause your audio.

Create a boolean to remember if your audio was playing or was on pause.

//initial status: audio is not playing
var status = false;
var audio = document.getElementById("myaudio");

function audioHandler(){
  if(status == false || audio.paused){
    audio.play();
    status = true;
  }else{
    audio.pause();
    status = false;
  }
}



回答2:


Check the media.paused property of your HTMLMediaElement

function play_pause(media) {
    if (media.paused) {
        media.play();
    else {
        media.pause();
    }
}

Use this in the handler on the element you want to control the action

var elm = document.getElementById('play_button'),
    audio =  document.getElementById('myaudio');
elm.addEventListener('click', function (e) {
    play_pause(audio);
});


来源:https://stackoverflow.com/questions/28740265/play-and-pause-with-onclick-on-the-same-img

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!