html5 video全屏播放/自动播放

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linysuccess/article/details/82491578

近期开始开发公司新版官网, 首页顶部(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>

其中php简单判断了一下是否是移动设备, 移动设备不展示视频(如果移动端展示的话, 需要解决iOS上无法自动播放的问题):

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标签样式的设置:

.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);
});

猜你喜欢

转载自blog.csdn.net/linysuccess/article/details/82491578