Files
gloabl_award_front/src/utils/flexible.js
2026-02-06 16:07:16 +08:00

88 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { getUniversalZoomLevel } from '@/utils/util'
import MyEvent from '@/utils/myEvent'
let flexible = (designWidth, maxWidth, minWidth) => {
var doc = document,
win = window,
docEl = doc.documentElement,
remStyle = document.createElement('style'),
tid
designWidth = designWidth || 1920
maxWidth = maxWidth || 2560
minWidth = minWidth || 1024
let oldDesignWidth = designWidth
// minWidth = minWidth || 1024;
function refreshRem() {
var width = docEl.getBoundingClientRect().width
var height = docEl.getBoundingClientRect().height
width = getUniversalZoomLevel() * width
height = getUniversalZoomLevel() * height
maxWidth = maxWidth || 1920
if (width < 1100) {
document.body.classList.add('ipad')
} else {
document.body.classList.remove('ipad')
}
if (width > 768) {
if (width / height > 1.98) width = height * 1.98
width > maxWidth && (width = maxWidth)
width < minWidth && (width = minWidth)
designWidth = oldDesignWidth
} else {
designWidth = 393
}
console.log(width, designWidth)
// var rem = width * 10 / designWidth;
var rem = Math.round((width * 10) / designWidth)
docEl.style.fontSize = rem + 'px'
remStyle.innerHTML = 'html{font-size:' + rem + 'px;}'
MyEvent.emit('remChange', rem)
}
// if (docEl.firstElementChild) {
// docEl.firstElementChild.appendChild(remStyle);
// } else {
// var wrap = doc.createElement("div");
// wrap.appendChild(remStyle);
// doc.write(wrap.innerHTML);
// wrap = null;
// }
//要等 wiewport 设置好后才能执行 refreshRem不然 refreshRem 会执行2次
refreshRem()
win.addEventListener(
'resize',
function () {
clearTimeout(tid) //防止执行两次
tid = setTimeout(refreshRem, 300)
},
false
)
win.addEventListener(
'pageshow',
function (e) {
if (e.persisted) {
// 浏览器后退的时候重新计算
clearTimeout(tid)
tid = setTimeout(refreshRem, 300)
}
},
false
)
if (doc.readyState === 'complete') {
doc.body.style.fontSize = '16px'
} else {
doc.addEventListener(
'DOMContentLoaded',
function (e) {
doc.body.style.fontSize = '16px'
},
false
)
}
}
export default flexible