VUE實現頁面等比例適配
阿新 • • 發佈:2021-08-23
實現原理
通過獲取頁面顯示內容的比例,去跟專案自己設定的比例比較,然後算出縮放比例,通過給相應節點設定scal 來縮放實現等比適配
實現頁面等比例顯示,重點是兩個知識點getBoundingClientRect()和transform: scale(x)。
getBoundingClientRect()
是用於獲取某個元素相對於視窗的位置集合。集合中有top, right, bottom, left等屬性。
#不需要傳引數 rectObject = object.getBoundingClientRect(); # 可以拿到這些返回值 /* rectObject.top:元素上邊到視窗上邊的距離; rectObject.right:元素右邊到視窗左邊的距離; rectObject.bottom:元素下邊到視窗上邊的距離; rectObject.left:元素左邊到視窗左邊的距離; rectObject.width:元素自身的寬度; rectObject.height:元素自身的高度; */
transform: scale()
是用於元素的縮放,不懂得可自行百度
實現方法
1、建立一個頁面節點
<template> <!-- cont 總是按高度或寬度鋪滿螢幕(cover) --> <div ref="cont" class="fit-screen-cont" > <!-- content 通過 scale(實際尺寸/設計尺寸) 來縮放實現等比適配 --> <div class="fit-content" :style="getFitContentStyle()" > <slot ref="content" class="fit-content"></slot> </div> </div> </template>
2、縮放方法,算出頁面縮放比例
updateScaleRatio(){ var rect = this.$refs.cont && this.$refs.cont.getBoundingClientRect(); var ratio = rect.width / rect.height; var innerRatio = this.width / this.height; if(ratio < innerRatio){ //Scale width var scaleRatio = rect.width/ this.width ; this.currentRatio = scaleRatio; } else{ scaleRatio = rect.height / this.height ; this.currentRatio = scaleRatio; } },
3、實現節點縮放的方法,將此方法繫結在建立的頁面節點上
getFitContentStyle(){
return {
width:this.width + 'px',
height:this.height + 'px',
transform:`scale(${this.currentRatio})`
}
}
4、通過頁面監聽頁面變化和頁面進入預設呼叫該方法,達到動態調節
mounted(){
window.addEventListener('resize',()=>{
this.updateScaleRatio();
})
this.updateScaleRatio();
},
完整程式碼
<template>
<!-- cont 總是按高度或寬度鋪滿螢幕(cover) -->
<div ref="cont" class="fit-screen-cont" >
<!-- content 通過 scale(實際尺寸/設計尺寸) 來縮放實現等比適配 -->
<div class="fit-content" :style="getFitContentStyle()" >
<slot ref="content" class="fit-content"></slot>
</div>
</div>
</template>
<script>
export default {
data(){
return {
width:1920,
height:1080,
currentRatio:1
}
},
mounted(){
window.addEventListener('resize',()=>{
this.updateScaleRatio();
})
this.updateScaleRatio();
},
methods:{
updateScaleRatio(){
var rect = this.$refs.cont && this.$refs.cont.getBoundingClientRect();
var ratio = rect.width / rect.height;
var innerRatio = this.width / this.height;
if(ratio < innerRatio){
//Scale width
var scaleRatio = rect.width/ this.width ;
this.currentRatio = scaleRatio;
}
else{
scaleRatio = rect.height / this.height ;
this.currentRatio = scaleRatio;
}
},
getFitContentStyle(){
return {
width:this.width + 'px',
height:this.height + 'px',
transform:`scale(${this.currentRatio})`
}
}
}
}
</script>
<style lang="scss" scoped>
.fit-screen-cont{
display:flex;
justify-content: center;
align-items: center;
width:100%;
height:100%;
flex:1;
overflow:hidden;
.fit-content{
flex:1;
transform-origin: center;
overflow: hidden;
position: absolute;
}
}
</style>