思路
获取当前视频容器宽度及视频原有宽高后,按比例设置高度
代码
<template>
<view v-if="src" class="video" style="margin:15rpx 0;">
<video
id="blessing-video"
class="blessing-video"
:style="videoHeight && 'height:' + videoHeight + 'px'"
:poster="poster"
:src="src"
@loadedmetadata="handleVideoLoaded"
/>
</view>
</template>
<script>
export default {
props: {
src: {
type: String,
default: undefined
},
poster: {
type: String,
default: undefined
}
},
data() {
return {
videoHeight: 0 // 初始化视频高度为0
};
},
methods: {
handleVideoLoaded(event) {
// 获取视频的原始宽度和高度
const videoWidth = event.target.width;
const videoHeight = event.target.height;
const query = uni.createSelectorQuery().in(this);
// 使用 select 方法选择元素,并获取元素的宽度和高度
query.select('.video').boundingClientRect(rect => {
console.log('容器的宽度:', rect.width);
// 计算视频的高度,保持宽高比例
this.videoHeight = (videoHeight / videoWidth) * rect.width;
}).exec();
}
}
}
</script>
<style scoped>
.blessing-video {
width: 100%;
border-radius:16rpx;
}
</style>
