寫在前面:網站輪播圖建議使用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);
}