App下載

在html5中使用video進行全屏播放與自動播放的代碼方法總結(jié)!

酒鞭名馬 2021-08-16 11:42:49 瀏覽數(shù) (7881)
反饋

今天由于在之前小編在項目中遇到的有關(guān)于:“在html5中使用video進行全屏播放與自動播放的代碼方法總結(jié)!”這方面的內(nèi)容,所以今天就來和大家分享有關(guān)于這方面的相關(guān)內(nèi)容!

近期開始開發(fā)公司新版官網(wǎng), 首頁頂部(header)是一個全屏播放的小視頻, 現(xiàn)簡單總結(jié)如下:

頁面代碼:

<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簡單判斷了一下是否是移動設(shè)備, 移動設(shè)備不展示視頻(如果移動端展示的話, 需要解決iOS上無法自動播放的問題):

ps: 如果H5頁面主要在微信瀏覽器中訪問,可以解決iOS上視頻自動播放的問題:解決iOS h5 audio自動播放(親測有效)

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標簽樣式

為了讓視頻占滿整個屏幕, 關(guān)鍵在于video標簽樣式的設(shè)置:

.home-video {
    z-index: 100;
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    object-fit: fill;/*這里是關(guān)鍵*/
    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);
});

頁面加載完成再次觸發(fā)播放,防止autoplay未生效:

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

那么以上就是有關(guān)于:“在html5中使用video進行全屏播放與自動播放的代碼方法總結(jié)!”這個方面的全部內(nèi)容更多有關(guān)于html5這方面的相關(guān)內(nèi)容我們都可以在W3Cschool中進行學(xué)習(xí)和了解!


0 人點贊