完整程序,已上传。
核心代码:
// 实际观察的元素
var actrulEle = null;
const scale = {
width: "1",
height: "1",
};
// * 设计稿尺寸(px)
const baseWidth = 1920;
const baseHeight = 1080;
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
/*
* @param { HTMLElement } watchEl 等待观察的外部元素
* @param { HTMLElement } el 实际需要响应外部元素改变而改变大小的内部元素
* @param { Boolean } 确认是否进行或者取消监听
*/
const useWatchElement = (watchEl, el, watchFlag = true) => {
actrulEle = el;
if (ob && !el && !watchFlag) {
ob.unobserve(watchEl);
return false;
}
ob.observe(watchEl);
};
const calcRate = (el) => {
const appRef = actrulEle;
if (!appRef) return;
// 获取待监听屏幕的长宽
const width = window.innerWidth;
const height = window.innerHeight;
// 当前宽高比
const currentRate = parseFloat((width / height).toFixed(5));
// console.log(width, height);
if (width != 0 && height != 0) {
if (currentRate > baseProportion) {
// 表示比基准宽高更宽
scale.width = ((height * baseProportion) / baseWidth).toFixed(5);
scale.height = (height / baseHeight).toFixed(5);
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
} else {
// 表示比基准宽高更高
scale.height = (width / baseProportion / baseHeight).toFixed(5);
scale.width = (width / baseWidth).toFixed(5);
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
}
} else {
return false;
}
};
let ids = null
// const ob = new ResizeObserver((e) => {
// const target = e[0].target;
// if (target.offsetWidth != 0 && target.offsetHeight != 0) {
// if (ids) {
// window.cancelAnimationFrame(ids)
// }
// if (target.offsetWidth < 300) { // 原来是600,现在改成400,因为如果改成600网页放大到500%的时候,内容还是会变大。现在固定不变了---wxc 2023-01-06
// // 宽度小于 600 的时候取消适配,大于等于 600 重新适配
// window.cancelAnimationFrame(ids)
// ids = null
// return false;
// }
// ids = window.requestAnimationFrame(() => calcRate(target))
// }
// });
let resizeTimer;
const debounceDelay = 100; // 适当延迟时间
const ob = new ResizeObserver((e) => {
const target = e[0].target;
if (target.offsetWidth === 0 || target.offsetHeight === 0) return;
if (target.offsetWidth < 300) { // 原来是600,现在改成400,因为如果改成600网页放大到500%的时候,内容还是会变大。现在固定不变了---wxc 2023-01-06
if (ids) {
window.cancelAnimationFrame(ids);
ids = null;
}
return;
}
// 清除之前的定时器
if (resizeTimer) {
clearTimeout(resizeTimer);
}
// 设置新的定时器
resizeTimer = setTimeout(() => {
if (ids) {
window.cancelAnimationFrame(ids);
}
ids = window.requestAnimationFrame(() => calcRate(target));
}, debounceDelay);
});
export default useWatchElement;