1.html
通過外層的div來給img對應的class,隱藏的img是得到img圖片請求回來時的原始尺寸。外層div是固定大小,因此,圖片有兩種情況去適應外部div的尺寸。一種是寬度大於高度的情況,一種是高度大於寬度的情況。
curSource.src是動態請求的img路徑
<div style='width:1349px;height:909px;'> <img :src="curSource.src" alt="" :class="isHeight ? 'hovImg' : 'verImg'"> <img ref='imgShow' :src="curSource.src" style="display:none"> <span v-if='infoState' class="info">加載失敗,請刷新頁面重試...</span> </div>
2.methods中 使用圖片加載完成時候的事件,來得到原始圖片的寬高,在按比例設置顯示圖片的樣式
this.$refs.imgShow.onload = () => { if (this.$refs.imgShow.width / this.$refs.imgShow.height > 1349 / 909) { this.isHeight = true } else { this.isHeight = false } this.spinShowTop = false }
3.data中
data () { return { isHeight: false, // 控制圖片的大小 curSourece.src, } }
4.style 一種是寬度大於高度的情況,一種是高度大於寬度的情況。
.hovImg{ width: 100%; height: auto; } .verImg{ width: auto; height: 100%; }