需求:自适应屏幕页面
问题:在页面高度不足时,需要对样式进行判断、修改,保证页面背景的完整。
已试过CSS修改调试,无法实现背景补全,所以采取了以下方法。
【template】
<div class="className1" :class="ratioKey? 'className2': 'className3'"> </div>
【data】
这里用了1500px的页面作为参考,当它在高度不足800px时出现背景缺失的问题,所以宽高比的临界值设为 1500/800 = 1.875。
并且根据此数值来测试,当宽高比大于1.875时,页面是否都会出现背景缺失问题,如有其他情况再进行细调。
data() {
return {
ratioKey: window.innerWidth / window.innerHeight > 1.875 ? true : false,
...
}}
【resize设置】
mounted() {
window.addEventListener('resize', this.handleResize, true);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize); // 移除绑定的事件
},
methods: {
handleResize() {
let that = this;
const ratio = window.innerWidth / window.innerHeight; // 获取当前窗口宽高比
// 这里可以根据窗口宽高比进行相应操作
if(ratio > 1.875) {
that.ratioKey = true
} else {
that.ratioKey = false
}
},
...
}