代码拉取完成,页面将自动刷新
// 通过更新目标DOM树上的所有Element节点来实现responsive,不需要手动实现水平垂直居中
function firstLetterUpper(str) {
const a = str[0];
const rest = str.slice(1);
return `${a.toUpperCase()}${rest}`;
}
// font-size -> fontSize
function camel(key) {
return key
.split("-")
.map((str, index) => (index !== 0 ? firstLetterUpper(str) : str))
.join("");
}
const responsiveAttrs = [
"width",
"height",
"row-gap",
"column-gap",
"line-height",
"border-width",
"font-size",
].map(camel);
const cloneDeep = (value) => JSON.parse(JSON.stringify(value));
function responsive2() {
const tasks = [];
const root = document.querySelector(".flex2");
const initialWidth = root.offsetWidth;
const initialHeight = root.offsetHeight;
const computedStyleMap = new Map();
function buildMap(element) {
if (element instanceof HTMLElement) {
computedStyleMap.set(element, cloneDeep(getComputedStyle(element)));
for (const child of element.children) {
buildMap(child);
}
}
}
buildMap(root);
const observer = new ResizeObserver((result) => {
const { inlineSize, blockSize } = result[0].contentBoxSize[0];
const wr = inlineSize / initialWidth;
const hr = blockSize / initialHeight;
const ratio = Math.min(wr, hr);
responsive(root, ratio);
tasks.forEach((task) => task());
tasks.length = 0;
});
observer.observe(root.parentElement);
function responsive(element, ratio) {
tasks.push(() => {
const style = computedStyleMap.get(element);
responsiveAttrs.forEach((attr) => {
const value = parseInt(style[attr]) * ratio;
element.style[attr] = `${value}px`;
});
});
for (const child of element.children) {
if (child instanceof HTMLElement) {
responsive(child, ratio);
}
}
}
}
responsive2();
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。