vue项目开发中,使用视频作为全屏背景的时候,当调整页面大小的时候,会导致视频位置偏移,解决思路,当窗口变化后,重新获取窗口大小,赋值给视频的父div即可。
实例代码
<template>
<div class="shipinbg" ref="videoRef2">
<video ref="videoRef" id="video" loop="true" muted class="shipin" autoplay="autoplay">
<source src="../assets/bg.mp4" type="video/mp4"/>
</video>
</div>
</template>
<script>
export default {
name: "videobg",
data() {
return {}
},
watch: {},
mounted() {
// 监听窗口大小变化事件
window.addEventListener('resize', this.resizeVideo);
// 初始加载时调整视频大小
this.resizeVideo();
},
beforeDestroy() {
// 移除窗口大小变化事件监听
window.removeEventListener('resize', this.resizeVideo);
},
methods: {
resizeVideo() {
const videoContainer = this.$refs.videoRef2;
const video = this.$refs.videoRef;
// 获取容器尺寸
const width = window.innerWidth;
const height = window.innerHeight;
// 设置视频容器和视频的宽高
videoContainer.style.width = width + 'px';
videoContainer.style.height = height + 'px';
video.style.width = '100%';
video.style.height = '100%';
}
}
}
</script>
<style lang="scss">
.shipinbg {
position: fixed;
width: 100%;
height: 100%;
object-fit: cover;
z-index: -1;
top: 0;
left: 0;
////屏蔽播放按钮
video::-webkit-media-controls {
display: none !important;
}
}
</style>