加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
responsive2.js 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
郑宝迪 提交于 2024-06-08 17:21 . init
// 通过更新目标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();
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化