效果如下:
1.自適應
2.判斷移動端橫豎屏
只需在app.vue中寫入如下代碼
<template>
<div id="app">
// 注意! src的圖片自己找一張gif圖
<div class="app-hint"
v-if="isScreen"><img src="./assets/image/screen.gif"
alt=""></div>
</div>
</template>
<script>
export default {
data() {
return {
screenWidth: document.body.clientWidth, // 網頁可見區域寬
screenHW: window.orientation, // 判斷橫豎屏
isScreen: false // 橫豎屏
};
},
watch: {
screenWidth(val) {
// 爲了避免頻繁觸發resize函數導致頁面卡頓,使用定時器
if (!this.timer) {
// 一旦監聽到的screenWidth值改變,就將其重新賦給data裏的screenWidth
this.screenWidth = val;
this.timer = true;
let that = this;
setTimeout(function() {
// 執行自適應代碼
that.bodyScale()
// 打印screenWidth變化的值
console.log(that.screenWidth);
that.timer = false;
}, 400);
}
},
screenHW () {
this.rotate()
}
},
methods: {
// 自適應代碼
bodyScale() {
var devicewidth = document.documentElement.clientWidth; //獲取當前分辨率下的可是區域寬度
var scale = devicewidth / 1960; // 分母——設計稿的尺寸
document.body.style.zoom = scale; //放大縮小相應倍數
},
// 判斷橫豎屏
rotate () {
if (this.screenHW == 180 || this.screenHW == 0) {
console.log('豎屏')
this.isScreen = true
} else if (this.screenHW == 90 || this.screenHW == -90) {
console.log('橫屏')
this.isScreen = false
}
}
},
created() {
// 執行自適應代碼
this.bodyScale()
},
mounted () {
// 監聽窗口大小
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth;
// 把橫豎屏的變化賦值
that.screenHW = window.orientation
})()
}
}
};
</script>