最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to pause video when click on new tab using javascript? - Stack Overflow

programmeradmin2浏览0评论

I'am working on video HTML Tag i want pause the audio when new Tab is open. Pls help to fix this issue.

<video autoplay onplay="clickplayer()" id="player" onended="endplayer()" fullscreen="true" controls onvolumechange="myFunction()"  ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">dik</video>

I'am working on video HTML Tag i want pause the audio when new Tab is open. Pls help to fix this issue.

<video autoplay onplay="clickplayer()" id="player" onended="endplayer()" fullscreen="true" controls onvolumechange="myFunction()"  ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">dik</video>
Share edited Jan 20, 2017 at 18:49 Mohammad 21.5k16 gold badges56 silver badges84 bronze badges asked Jan 9, 2017 at 10:23 chozhanchozhan 1812 silver badges17 bronze badges 1
  • Do you want pause audio and keep video playing or both pause? – Mohammad Commented Jan 10, 2017 at 13:28
Add a ment  | 

2 Answers 2

Reset to default 6

You need to detect the window de-focus event first to do so. Here is an example:

HTML:

 <video id="video" width="400" controls>
   <source src="http://www.w3schools./html/mov_bbb.mp4" type="video/mp4">
 </video>

JS:

document.addEventListener("visibilitychange", onchange);
function onchange (evt) {
   document.getElementById("video").pause();
}

You can find full example Here

Note that, same method applies to Audio tags as well.

The visibilitychange event is fired when the content of a tab has bee visible or has been hidden.

You should detect tab visibility on visibilitychange event and pause video if tab is hidden.

var focused = true;
document.addEventListener("visibilitychange", function () {
  focused = !focused;
  if (!focused)
    document.getElementById("video").pause();
});
<video id="video" width="400" controls>
   <source src="http://www.w3schools./html/mov_bbb.mp4" type="video/mp4">
</video>

发布评论

评论列表(0)

  1. 暂无评论