@morjs/runtime-web
Version:
mor runtime for web
49 lines • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.autoSyncRootFontSize = exports.rpxToRem = exports.setRootFontSizeForRem = void 0;
/**
* 用于 rpx => rem 的转换
*/
let ROOT_VALUE = 2 * 16;
function updateFontSize(rootFontSize) {
window.document.documentElement.style.setProperty('font-size', (rootFontSize * window.document.documentElement.clientWidth) / 375 + 'px');
}
/**
* 设置根节点 font-size
*/
function setRootFontSizeForRem(rootFontSize) {
ROOT_VALUE = 2 * rootFontSize;
updateFontSize(rootFontSize);
window.addEventListener('resize', () => {
updateFontSize(rootFontSize);
});
}
exports.setRootFontSizeForRem = setRootFontSizeForRem;
function rpxToRem(rpxValue) {
return `${rpxValue / ROOT_VALUE}rem`;
}
exports.rpxToRem = rpxToRem;
window.$rpxToRem = rpxToRem;
/**
* 自动同步根节点的 font-size
* 并设置 ROOT_VALUE
*/
function autoSyncRootFontSize(updateOnResize = true) {
var _a, _b, _c;
const rootStyle = (_b = (_a = window === null || window === void 0 ? void 0 : window.document) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.style;
const fontSize = String(((_c = rootStyle === null || rootStyle === void 0 ? void 0 : rootStyle.getPropertyValue) === null || _c === void 0 ? void 0 : _c.call(rootStyle, 'font-size')) || '')
.trim()
.replace(/([0-9]+).+/, '$1');
if (fontSize) {
ROOT_VALUE =
((Number(fontSize) * 375) / window.document.documentElement.clientWidth) *
2;
}
if (updateOnResize) {
window.addEventListener('resize', () => {
autoSyncRootFontSize(false);
});
}
}
exports.autoSyncRootFontSize = autoSyncRootFontSize;
//# sourceMappingURL=rpx.js.map