用户切换标签时暂停html5视频 [英] Pause html5 video when user switches tab
问题描述
我的网页上嵌入了HTML5视频:
I have an HTML5 video embedded on my webpage:
<video id="myvideo">
<source src="videos/myvideo.mp4">
</video>
当用户转到其他浏览器窗口或标签时,我还有一些jQuery可以暂停视频.并在用户返回时播放视频:
And I have a bit of jQuery to pause the video when the user goes to a different browser window or tab. And also to play the video when the user returns:
// pause when the user leaves this window/tab
$(window).blur(function(){
$('#myvideo').get(0).pause();
});
// play when the user returns to this window/tab
$(window).focus(function(){
$('#myvideo').get(0).play();
});
问题是,即使用户看到视频并且没有切换选项卡,即使用户单击位置栏或将焦点放在其他OS窗口上,也会暂停视频.
The problem with this is that will also pause the video if the user clicks on the location bar or focuses on a different OS window, even though the video is visible and the user hasn't switched tabs.
是否可以根据当前标签页是否打开(但不一定要聚焦)来暂停/播放视频?
Is there a way to pause/play the video based on whether the current tab is open (but not necessarily focused)?
推荐答案
发布问题后,我几乎立即找到了答案. 页面可见性API 让您知道网页何时可见或焦点对准.有一个不错的jQuery填充程序,名为 jquery-visibility ,它为跨浏览器解决方案提供了干净的API.使用它,您可以执行以下操作:
I found the answer almost immediately after posting the question. The Page Visibility API allows you to know when a webpage is visible or in focus. There's a nice jQuery shim called jquery-visibility that provides a clean API for a cross-browser solution. Using it you can do something like:
$(document).on('show.visibility', function() {
$('#myvideo').get(0).play();
});
$(document).on('hide.visibility', function() {
$('#myvideo').get(0).pause();
});
这篇关于用户切换标签时暂停html5视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!