以下是一个示例代码,演示了如何在Vue中设置全屏动态背景:

<template>
  <div class="fullscreen-bg">
    <div class="overlay"></div>
    <video class="bg-video" autoplay loop muted>
      <source src="your-video-file.mp4" type="video/mp4">
    </video>
    <div class="content">
      <!-- 页面内容 -->
    </div>
  </div>
</template>

<script>
export default {
  name: 'FullscreenBackground',
  mounted() {
    // 设置视频尺寸与窗口尺寸一致
    window.addEventListener('resize', this.resizeVideo);
    this.resizeVideo();
  },
  methods: {
    resizeVideo() {
      const video = document.querySelector('.bg-video');
      video.style.width = `${window.innerWidth}px`;
      video.style.height = `${window.innerHeight}px`;
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeVideo);
  }
}
</script>

<style>
.fullscreen-bg {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.bg-video {
  position: absolute;
  top: 0;
  left: 0;
  object-fit: cover;
}

.content {
  position: relative;
  z-index: 1;
  /* 其他样式 */
}
</style>

在上面的代码中,我们使用了一个div元素作为全屏容器,并设置了宽度为100%、高度为100vh(视口高度)。overlay元素是一个半透明的层,用于蒙版效果。bg-video元素是用来播放背景视频的,我们使用了一个video标签,并设置了autoplayloopmuted属性,分别表示自动播放、循环播放和静音。你需要将your-video-file.mp4替换为你自己的视频文件路径。

mounted钩子中,我们添加了一个resize事件监听器,当窗口大小改变时,调用resizeVideo方法来调整视频的尺寸,使其始终与窗口尺寸保持一致。resizeVideo方法通过获取.bg-video元素并设置其宽高来实现。

最后,在组件销毁之前,我们移除了resize事件监听器,以免引起内存泄漏。

你可以根据自己的需求在.content元素中添加其他页面内容。


原文地址: https://www.cveoy.top/t/topic/jeqj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录