html5 video全屏播放/自动播放
近期开始开发公司新版官网, 首页顶部(header)是一个全屏播放的小视频, 现简单总结如下:
页面代码
<header class="header" style="width:100%;position: relative;"> <?php if(!Helper::isMobile()) { ?> <video id="homeVideo" class="home-video" autoplay loop muted poster="res/video/cover.jpg"> <source src="res/video/home_video.mp4" type="video/mp4"> </video> <?php } ?> </header>
class Helper { public static function isMobile() { if (preg_match("/(iPhone|iPod|Android|ios|iPad)/i", $_SERVER[HTTP_USER_AGENT])) { return true; } else { return false; } } }
video标签样式
为了让视频占满整个屏幕, 关键在于video标签样式的设置:
.home-video { z-index: 100; position: absolute; top: 50%; left: 50%; min-width: 100%; min-height: 100%; object-fit: fill;/*这里是关键*/ width: auto; height: auto; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); background: url(../video/cover.jpg) no-repeat; background-size: cover; }
视频跟随浏览器窗口大小的改变:
$(.home-video).height(window.innerHeight); $(.header).height(window.innerHeight); $(window).resize(function() { $(.home-video).attr(height, window.innerHeight); $(.home-video).attr(width, window.innerWidth); $(.header).height(window.innerHeight); });
页面加载完成再次触发播放,防止autoplay未生效
document.getElementById(homeVideo).play();
值得注意的是,video标签必须加muted属性(静音播放),否则在Chrome浏览器下调用play()会报错:
DOMException: play() failed because the user didnt interact with the document first.
这是因为从Chrome从66版本开始,为了避免打扰用户,自动播放时,必须是静音播放。 能不能绕过这个限制呢?不妨试试效果:
document.getElementById(homeVideo).play(); //在play之后加一个延时,清除video的muted属性 setTimeout(function(){ document.getElementById(homeVideo).removeAttribute(muted); }, 100);
官网成品请参考: