devicePixelRatio.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class DevicePixelRatio {
  2. constructor() {
  3. // this.flag = false;
  4. }
  5. // 获取系统类型
  6. _getSystem() {
  7. // let flag = false;
  8. var agent = navigator.userAgent.toLowerCase();
  9. // var isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  10. // if(isMac) {
  11. // return false;
  12. // }
  13. // 现只针对windows处理,其它系统暂无该情况,如有,继续在此添加
  14. if (agent.indexOf('windows') >= 0) {
  15. return true;
  16. }
  17. }
  18. // 获取页面缩放比例
  19. // _getDevicePixelRatio() {
  20. // let t = this;
  21. // }
  22. // 监听方法兼容写法
  23. _addHandler(element, type, handler) {
  24. if (element.addEventListener) {
  25. element.addEventListener(type, handler, false);
  26. } else if (element.attachEvent) {
  27. element.attachEvent('on' + type, handler);
  28. } else {
  29. element['on' + type] = handler;
  30. }
  31. }
  32. // 校正浏览器缩放比例
  33. _correct() {
  34. let t = this;
  35. // 页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。
  36. document.getElementsByTagName('body')[0].style.zoom = 1 / window.devicePixelRatio;
  37. }
  38. // 监听页面缩放
  39. _watch() {
  40. let t = this;
  41. t._addHandler(window, 'resize', function() { // 注意这个方法是解决全局有两个window.resize
  42. // 重新校正
  43. t._correct()
  44. })
  45. }
  46. // 初始化页面比例
  47. init() {
  48. let t = this;
  49. if (t._getSystem()) { // 判断设备,目前只在windows系统下校正浏览器缩放比例
  50. // 初始化页面校正浏览器缩放比例
  51. t._correct();
  52. // 开启监听页面缩放
  53. t._watch();
  54. }
  55. }
  56. }
  57. export default DevicePixelRatio;