为了对界面进行优化,我决定使用视频作为网站首页的背景,这里就要面临一个如何将视频作为网页背景的问题。
在此之前,我尝试过用图片做网页背景。当时我使用的方法是在div
标签中嵌套img
标签,并将此div
以及包含了页面中其他内容的div
的position
设置为absolute
,然后规定位置。所以我尝试了用同样的方法制作视频背景,只是将img
标签换为了video
标签。这个尝试是成功的,视频成功地出现在了其他页面内容下方。接下来只需要优化一下背景就可以了。
优化背景要做的一件比较重要的事情就是让视频背景能够自适应窗口大小。为此,我们要在网页创建时加入一个窗口改变事件监听器,并向其中添加相应的改变视频及组件的大小的方法。代码如下:
resize() {
this.setContainerHeight();
if (this.videoCanPlay()) {
this.setVideoSize();
}
},
videoCanPlay() {
return !!this.$refs.video.canPlayType;
},
setContainerHeight() {
this.$el.style.height = `${window.innerHeight}px`;
},
setVideoSize() {
var width,
height,
containerRatio = this.$el.offsetWidth / this.$el.offsetHeight;
if (containerRatio > this.videoRatio) {
width = this.$el.offsetWidth;
} else {
height = this.$el.offsetHeight;
}
this.$refs.video.style.width = width ? `${width}px` : "auto";
this.$refs.video.style.height = height ? `${height}px` : "auto";
},
mounted() {
this.setImageUrl();
this.setContainerHeight();
if (this.videoCanPlay()) {
this.$refs.video.oncanplay = () => {
if (!this.$refs.video) return;
this.videoRatio =
this.$refs.video.videoWidth / this.$refs.video.videoHeight;
this.setVideoSize();
this.$refs.video.style.visibility = "visible";
};
}
window.addEventListener("resize", this.resize);
},
beforeDestroy() {
window.removeEventListener("resize", this.resize);
},