本文講述如何實現擁有酷炫背景視頻的登陸頁面,瀏覽器窗口隨意拉伸,背景視頻及前景登陸組件均能完美適配,背景視頻可始終鋪滿窗口,前景組件始終居中,視頻的內容始終獲得最大限度的保留,能夠獲得最好的視覺效果。而且基於 Vue.js 2.0 全家桶。具體效果以下圖所示:javascript
最終效果能夠翻到文章最後觀看。css
國外有一個很好的網站「Coverr」,提供了完善的教程和視頻資源,幫助前端開發者構建酷炫的背景視頻主頁,網站效果示例以下圖所示:html
教程以下所示:前端
從圖中以及個人實踐能夠得出如下觀點:vue
首先基於腳手架工具 vue-cli 來建立一個使用 vue-loader 的項目,構建完畢後,在相應目錄下建立「.vue」文件,做爲登陸頁面的模板文件,具體細節再也不贅述。本節內容僅侷限於該.vue文件。java
基於需求,對 Coverr 提供的 HTML 模板進行了細微修改,結果以下:jquery
<template> <div class="homepage-hero-module"> <div class="video-container"> <div :style="fixStyle" class="filter"></div> <video :style="fixStyle" autoplay loop class="fillWidth" v-on:canplay="canplay"> <source src="PATH_TO_MP4" type="video/mp4"/> 瀏覽器不支持 video 標籤,建議升級瀏覽器。 <source src="PATH_TO_WEBM" type="video/webm"/> 瀏覽器不支持 video 標籤,建議升級瀏覽器。 </video> <div class="poster hidden" v-if="!vedioCanPlay"> <img :style="fixStyle" src="PATH_TO_JPEG" alt=""> </div> </div> </div> </template>
模板中,filter
類的 div
標籤是一層背景視頻的蒙版,能夠經過蒙版控制視頻的亮暗以及色溫等。web
video
標籤爲標準的 HTML5 標籤,提供兩種格式的視頻以及一張圖片佔位符,背景視頻在加載完畢後即自動播放。vue-cli
Coverr 提供的原始模板,直接調試,頁面只顯示圖片,而沒法播放視頻,經過使用 Vue.js 的 v-if
指令解決了該問題。瀏覽器
對原始模板 CSS 代碼進行了大幅精簡,修改後的 CSS 代碼以下所示:
<style scoped> .homepage-hero-module, .video-container { position: relative; height: 100vh; overflow: hidden; } .video-container .poster img, .video-container video { z-index: 0; position: absolute; } .video-container .filter { z-index: 1; position: absolute; background: rgba(0, 0, 0, 0.4); } </style>
因爲大多數樣式均被項目全局修改了,因此在此專用於此模板的樣式只剩下三條,簡要說明以下:
<script> export default { name: 'login', data() { return { vedioCanPlay: false, fixStyle: '' } }, methods: { canplay() { this.vedioCanPlay = true } }, mounted: function() { window.onresize = () => { const windowWidth = document.body.clientWidth const windowHeight = document.body.clientHeight const windowAspectRatio = windowHeight / windowWidth let videoWidth let videoHeight if (windowAspectRatio < 0.5625) { videoWidth = windowWidth videoHeight = videoWidth * 0.5625 this.fixStyle = { height: windowWidth * 0.5625 + 'px', width: windowWidth + 'px', 'margin-bottom': (windowHeight - videoHeight) / 2 + 'px', 'margin-left': 'initial' } } else { videoHeight = windowHeight videoWidth = videoHeight / 0.5625 this.fixStyle = { height: windowHeight + 'px', width: windowHeight / 0.5625 + 'px', 'margin-left': (windowWidth - videoWidth) / 2 + 'px', 'margin-bottom': 'initial' } } } window.onresize() } } </script>
以上代碼中最重要的部分是對 window 對象的 onresize 事件的監聽。當窗口大小更改時,程序同步修改 video 及蒙版 dom 的尺寸,使得視頻的最窄的邊始終撐滿瀏覽器的窗口,而長的邊左右兩邊被均勻地裁減。
這樣操做,可使得視頻不會被拉伸,視頻中心始終位於瀏覽器的中心,而且在隨意拉伸瀏覽器窗口時,視頻的內容始終獲得最大限度的保留,而且能夠獲得最好的視覺效果。
最終效果以下所示: