在前端vue
項(xiàng)目開發(fā)中經(jīng)常會(huì)用到走馬燈的場(chǎng)景,然而在采用Element-ui的情況下,el-carousel
走馬燈組件有一個(gè)默認(rèn)的固定高度300px
。如下所示:
.el-carousel__container {
position: relative;
height: 300px; // element-ui 默認(rèn)高度
}
這樣會(huì)導(dǎo)致網(wǎng)頁(yè)的全屏的banner
被壓縮或拉伸,變形十分難看,在一個(gè)認(rèn)真的切圖仔眼里是無(wú)法容忍的。然而業(yè)務(wù)方在使用的時(shí)候沒有按照相關(guān)圖片規(guī)范來(lái)上傳符合規(guī)格的圖片大小。所以我們需要在程序中開發(fā)根據(jù)業(yè)務(wù)后臺(tái)上傳的圖片大小來(lái)動(dòng)態(tài)渲染走馬燈的高度。
下面我們來(lái)看看具體的代碼實(shí)現(xiàn):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-436433.html
<template>
<!--banner 組件-->
<el-carousel
:height="imgHeight"
style="width:100%;"
indicator-position="none"
:arrow="bannerList.length>1 ? 'hover' : 'never'"
:loop="true"
:autoplay="true"
>
<el-carousel-item v-for="(item,index) in bannerList" :key="index">
<template v-if="item.jumpType">
<el-image ref="image"
style="width:100%;"
:src="item.image"
fit="fit"
class="banner-img" />
</template>
</el-carousel-item>
</el-carousel>
</template>
<script>
export default {
props:{
bannerList:{
type: Array,
require: false,
default: () => []
}
},
data(){
return {
imgHeight: ''
}
},
mounted(){
this.imgLoad();
// 監(jiān)聽窗口變動(dòng)大小計(jì)算banner高度
window.addEventListener("resize", () => {
this.imgLoad()
});
},
methods:{
// 獲取圖片的實(shí)際長(zhǎng)度和寬度
getImgAttr (url, callback) {
let img = new Image()
img.src = url
if (img.complete) {
callback(img.width, img.height);
// console.log(img.width, img.height, 'img.width, img.height')
} else {
img.onload = function () {
callback(img.width, img.height)
img.onload = null
}
}
},
imgLoad() {
this.$nextTick(function() {
// 定義頁(yè)面初始的走馬燈高度, 默認(rèn)以第一張圖片高度
if (this.bannerList.length) {
this.getImgAttr(this.bannerList[0].image, (width, height) => {
// 獲取屏寬計(jì)算圖片容器高度
let screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
this.imgHeight = height / width * screenWidth + 'px'
// console.log(this.imgHeight, 'this.imgHeight')
})
}
});
},
}
}
</script>
寫到這兒基本上解決了圖片變形問(wèn)題。注意:
組件的mounted
鉤子中監(jiān)聽屏幕大小改變,在組件銷毀時(shí)監(jiān)聽盡可能的要移除事件監(jiān)聽,這里程序與文章相關(guān)不大省略掉了。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-436433.html
到了這里,關(guān)于Element-ui的Carousel走馬燈組件動(dòng)態(tài)渲染高度的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!