寫在前面:網站輪播圖建議使用swiper組件,很是方便快捷。element-ui
接手一個項目,輪播圖是用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層的高度,計算方式:根據瀏覽器的寬度計算等比的圖片高度:ide
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:ui
mounted () { this.setSize(); const that = this; window.addEventListener('resize', function() { that.screenWidth = $(window).width(); that.setSize(); }, false); }