vue项目中el-carousel默认高度300问题

本文解决Vue项目中使用Element UI的el-carousel组件时,默认高度导致的图片变形和自适应问题。通过调整CSS样式和使用JavaScript动态计算图片高度,确保在不同屏幕尺寸下banner图能保持良好的视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue项目中el-carousel默认高度300问题

项目需要适配PC端的各种宽度以及移动端缩放看起来不乱,但是banner图设置固定高度之后,宽度变小之后图片会变形,不能自适应。
.banner, .banner .block, .banner >>> .el-carousel .el-carousel--horizontal, .block >>> .el-carousel__container{
    height: 640px!important;
    overflow: hidden;
  }

解决办法:

html
<div class="block">
   <el-carousel trigger="click" id = 'el-carousel'>
      <el-carousel-item v-for="(item, index) in banners" :key="index">
        <img :src="item.img" alt="">
      </el-carousel-item>
    </el-carousel>
</div>
css
.banner .block img{
    width: 100%;
 }
.banner, .banner .block, .banner >>> .el-carousel .el-carousel--horizontal, .block >>> .el-carousel__container{
    height: 100%!important;
    overflow: hidden;
}
js
export default {
    data() {
      return {
        banners: [],
        bannerHeight: 640,
        screenWidth: 1920,
      };
    },
    methods: {
      setSize1: function() {
        var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        this.screenWidth = width;
        //图片                高 / 宽  500 / 1920
        this.bannerHeight = 640 / 1920 * this.screenWidth
        document.getElementById('el-carousel').style.height = this.bannerHeight + 'px';
      },
      setSize: function() {
        this.bannerHeight = 640 / 1920 * this.screenWidth
        document.getElementById('el-carousel').style.height = this.bannerHeight + 'px';
      },
    },
    mounted(){
      this.setSize1();
      const that = this;
      //监听浏览器窗口大小改变
      window.addEventListener('resize', function() {
        var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        that.screenWidth = width;
        that.setSize();
      }, false);
    },

原文章:
用element-ui的走马灯carousel轻松实现自适应全屏banner图 解决el-carousel默认高度300问题 组件代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值