pc端web页面开发时,发现windows系统常常推荐用户使用125%、150%比例的缩放窗口,这样致使web页面被进行缩放,除此以外还有人为的按钮缩放。故此,在页面devicePixelRatio(设备像素比例)变化后,经过计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。vue
判断是否是需处理的系统,目前只有windows系统下有此问题git
_getSystem() {
let flag = false;
var agent = navigator.userAgent.toLowerCase();
//var isMac = /macintosh|mac os x/i.test(navigator.userAgent);
//if(isMac) {
// return false;
//}
//现只针对windows处理,其它系统暂无该状况,若有,继续在此添加
if(agent.indexOf("windows") >= 0) {
return true;
}
}
复制代码
_addHandler(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
复制代码
_correct() {
let t = this;
document.getElementsByTagName('body')[0].style.zoom = 1 / window.devicePixelRatio;
}
复制代码
_watch() {
let t = this;
t._addHandler(window, 'resize', function() { //注意这个方法是解决全局有两个window.resize
//从新校订
t._correct()
})
}
复制代码
init() {
let t = this;
if(t._getSystem()) { //判断设备,目前只在windows系统下校订浏览器缩放比例
//初始化页面校订浏览器缩放比例
t._correct();
//开启监听页面缩放
t._watch();
}
}
复制代码
/** * @author trsoliu * @date 2019-12-05 * @description 校订windows页面在系统进行缩放后致使页面被放大的问题,一般放大比例是125%、150% * **/
class DevicePixelRatio {
constructor() {
//this.flag = false;
}
//获取系统类型
_getSystem() {
let flag = false;
var agent = navigator.userAgent.toLowerCase();
// var isMac = /macintosh|mac os x/i.test(navigator.userAgent);
// if(isMac) {
// return false;
// }
//现只针对windows处理,其它系统暂无该状况,若有,继续在此添加
if(agent.indexOf("windows") >= 0) {
return true;
}
}
//获取页面缩放比例
// _getDevicePixelRatio() {
// let t = this;
// }
//监听方法兼容写法
_addHandler(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
//校订浏览器缩放比例
_correct() {
let t = this;
//页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。
document.getElementsByTagName('body')[0].style.zoom = 1 / window.devicePixelRatio;
}
//监听页面缩放
_watch() {
let t = this;
t._addHandler(window, 'resize', function() { //注意这个方法是解决全局有两个window.resize
//从新校订
t._correct()
})
}
//初始化页面比例
init() {
let t = this;
if(t._getSystem()) { //判断设备,目前只在windows系统下校订浏览器缩放比例
//初始化页面校订浏览器缩放比例
t._correct();
//开启监听页面缩放
t._watch();
}
}
}
export default DevicePixelRatio;
复制代码
//vue使用
//在app.vue或者其它全局的文件中引入函数
import DevicePixelRatio from './XX/assets/js/libs/devicePixelRatio.js';
//在vue生命周期created中添加
created() {
new DevicePixelRatio().init();
}
//其它使用
//全局引入devicePixelRatio.js
//在页面加载之时,调用此方法初始化页面比例
new DevicePixelRatio().init();
复制代码
页面在加载之时会检测页面的设备像素比例,而后重置页面比例,以后启动监听页面改变,发现变化就重置页面比例;github
有建议或问题能够加群qq交流
535798405
,github:github.com/trsoliuweb