element-ui 轮播图设置动态高度

475 阅读1分钟

element ui的轮播图 el-carousel
组件使用如下,有height属性

<el-carousel indicator-position="none" :height="imgHeight">
    <el-carousel-item v-for="(item, index) in bannerList" :key="item.id">
        <img :src="item.img_url" alt="" />
    </el-carousel-item>
</el-carousel>  

轮播图是通栏的,高度需要随着宽度的变化而变化,如果高度固定,图片将会显示不完整
所以需要想办法变化 我们图片宽高是有比例的,所以这里就好做了
js代码如下

// 这里默认给了个高度,防止挂载后会闪烁
const imgHeight = ref('400px');
function onresize() {
    let winWidth = window.innerWidth;
    // 这里图片高宽比是 4: 25
    imgHeight.value = (5 / 24) * winWidth + 'px';
}

onMounted(() => {
    onresize();
    window.addEventListener('resize', onresize);
});

onUnmounted(() => {
    window.removeEventListener('resize', onresize);
});

然后我们的轮播图随宽度,高度自适应就做好了。

欢迎学习沟通交流