使用HTML5视频标签退出全屏

10

我试图让视频在播放结束后退出全屏,但它不会自动退出。我搜索了一些方法,但就是无法使其正常工作。我正在使用谷歌浏览器(版本15)和iPad2上的iOS5进行测试。

这是我使用的代码:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
  $("#myVideoTag").on('ended', function(){
    webkitExitFullScreen();
  });
});

</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>854x480</title>
</head>
<body>
<video  width="854" height="480"
        src="video/854x480-Template_1.mp4"
        poster="images/poster.jpg"
        id="myVideoTag"
        type="video/mp4"
        preload="auto"
        autobuffer
        controls>
  <p>Requires HTML5 capable browser.</p>
</video>

</body>
</html>

非常感谢您的帮助。

3个回答

16

webkitExitFullScreenvideo 元素的一个方法,因此必须以这种方式调用:

videoElement.webkitExitFullscreen();
//or
$("#myVideoTag")[0].webkitExitFullscreen();
//or, without needing jQuery
document.getElementsById('myVideoTag').webkitExitFullscreen();

由于它在事件处理程序内部,this会成为已经endedvideo,因此:

$("#myVideoTag").on('ended', function(){
  this.webkitExitFullscreen();
});
这有点复杂,因为webkitExitFullscreen只在基于Webkit的浏览器(Safari、Chrome、Opera)中起作用,所以您可以在MDN上了解有关其正确使用的更多信息。

谢谢cbaigorri。就是这样!感谢您的帮助。 - ShockTower
5
注意!函数名应该是 webkitExitFullscreen 而不是 webkitExitFullScreen(注意小写字母"s")。 - Svilen Ivanov
4
任何人都不应该点赞只支持webkit的答案。请更新您的答案以支持所有浏览器。只支持一个渲染引擎的开发人员根本就不是开发人员! - John
有时候你只需要一个 WebKit 的答案,因为其他浏览器更容易使用。 - Mark Rogers

10

我知道这个问题已经有答案了,但是这里是我最终在所有浏览器上使用的关闭全屏视频的小代码片段。

目前已在Chrome、IE11和Firefox上测试通过:

$("#myVideoTag").on('ended', function(){
    if (document.exitFullscreen) {
        document.exitFullscreen(); // Standard
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen(); // Blink
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen(); // Gecko
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen(); // Old IE
    }
});

你还可以像这样找到当前的全屏元素(如果有):

  var fullscreenElement = document.fullscreenElement || 
   document.mozFullScreenElement || document.webkitFullscreenElement;

来源:https://www.sitepoint.com/use-html5-full-screen-api/

我想添加答案,因为这是我在寻找解决方案时遇到的第一个问题。


2

感谢cbaigorri,使用.webkitExitFullscreen()非常好用。

我在视频播放完成后使用以下代码退出全屏:

<script type="text/javascript">
function CloseVideo() {
    document.getElementsByTagName('video')[0].webkitExitFullscreen();
}
</script>

<video controls onended=CloseVideo() >
    <source src="video.mp4" type="video/mp4">
</video>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接