用element-ui的走馬燈carousel輕松實現自適應全屏banner圖


寫在前面:網站輪播圖建議使用swiper組件,非常方便快捷。vue輪播圖插件之vue-awesome-swiper

接手一個項目,輪播圖是用element-ui的carousel實現的,看起來效果還不錯,只是固定寬高,並未做適配,於是將就代碼做下修改,以適配各種顯示器屏幕。


    <el-carousel indicator-position="outside" :height="bannerHeight + 'px'">
     <el-carousel-item v-for="(item,index) in BannerImg">
       <img src="../../assets/images/banner1.jpg" v-if="index == 0" class="bannerImg" />
       <img src="../../assets/images/banner2.jpg" v-if="index == 1" class="bannerImg" />
       <img src="../../assets/images/banner3.jpg" v-if="index == 2" class="bannerImg" />
     </el-carousel-item>
   </el-carousel>



bannerHeight屬性用來控制banner層的高度,計算方式:根據瀏覽器的寬度計算等比的圖片高度:


setSize: function () {
    this.bannerHeight = 740 / 2560 * this.screenWidth
    if(this.bannerHeight > 740) this.bannerHeight = 740
    if(this.bannerHeight < 360) this.bannerHeight = 360
  }

給img加樣式:


.bannerImg{
    width: 100%;
    height: inherit;
    min-height: 360px;
    min-width: 1400px;
  }
  

大功告成!為了讓改變瀏覽器也能適配,監聽一下瀏覽器resize:


mounted () {
  this.setSize();
  const that = this;
  window.addEventListener('resize', function() {
    that.screenWidth = $(window).width();
    that.setSize();
  }, false);
}

原文地址:https://segmentfault.com/a/1190000014811442


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM