Implementation example of HTML5 video full screen play / auto play

Time:2020-11-30

Recently, we started to develop a new version of the company’s official website. At the top of the front page is a small video playing in full screen

Page code


<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 simply determines whether it is a mobile device, and the mobile device does not display the video (if the mobile terminal displays it, it needs to solve the problem that the IOS can’t play automatically)

PS: if the H5 page is mainly accessed in the wechat browser, it can solve the problem of automatic video playback on IOS: solve the automatic playback of IOS H5 audio (valid for pro test)


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 label style

In order to make the video occupy the whole screen, the key is to set the video label style:

.home-video {
    z-index: 100;
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    Object fit: fill; / * here is the key*/
    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;
}

The video follows the size of the browser window:


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

After the page is loaded, the playback will be triggered again to prevent the autoplay from not taking effect


document.getElementById('homeVideo').play();

This article about the implementation of HTML5 video full screen play / auto play is introduced here. For more related HTML5 video full screen playback / auto play content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!