video-player vue 如何在封面上加播放按钮
时间: 2023-10-30 11:58:05 浏览: 38
你可以通过在视频封面上覆盖一个播放按钮图标的方式实现这个功能。具体步骤如下:
1. 在模板中添加一个 `<div>` 元素,作为视频封面的容器,并设置其样式和背景图片。
```
<template>
<div class="video-cover" :style="{ backgroundImage: `url(${coverUrl})` }">
<!-- 在这里添加播放按钮图标 -->
<div class="play-button"></div>
</div>
</template>
<style>
.video-cover {
position: relative;
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
}
.play-button {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80px;
height: 80px;
background-image: url(./play-icon.png);
background-size: contain;
background-repeat: no-repeat;
cursor: pointer;
}
</style>
```
2. 在组件的 `data` 中添加一个 `coverUrl` 属性,用于存储视频封面的 URL。
```
export default {
data() {
return {
coverUrl: 'https://example.com/cover.jpg',
};
},
};
```
3. 在 `mounted` 钩子函数中,为播放按钮绑定 `click` 事件,并在事件处理函数中调用视频播放的方法。
```
export default {
mounted() {
const playButton = this.$el.querySelector('.play-button');
playButton.addEventListener('click', () => {
this.$refs.player.play();
});
},
};
```
其中,`$refs.player` 是一个指向 `<video>` 元素的引用,你需要在模板中添加一个 `<video>` 元素,并设置它的 `src` 属性为视频的 URL。
```
<template>
<div class="video-cover" :style="{ backgroundImage: `url(${coverUrl})` }">
<div class="play-button"></div>
<video ref="player" :src="videoUrl"></video>
</div>
</template>
<script>
export default {
data() {
return {
coverUrl: 'https://example.com/cover.jpg',
videoUrl: 'https://example.com/video.mp4',
};
},
mounted() {
const playButton = this.$el.querySelector('.play-button');
playButton.addEventListener('click', () => {
this.$refs.player.play();
});
},
};
</script>
```