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问题 组件代码

Logo

前往低代码交流专区

更多推荐