前端-如何始终平均分配剩余空间
如何在布局中始终平均分配剩余空间给间隙(gap)
【前端-如何始终平均分配剩余空间】不废话,直接上代码:
import { useEffect } from "react";
import "./styles.css";
export default function App() {
function dynamicCalculate() {
const container = document.getElementById("container") as HTMLElement;
const item = container.firstElementChild as HTMLElement;
let W: number;
// Width of container.
let w: number;
// Width of item.
let b: number;
// Border's width of item.
let minGap: number;
// Minimum gap between items.
let gap: number;
// Gap between items.
let n: number;
// Number of items in one row.W = container.clientWidth;
w = item.clientWidth;
b = +window.getComputedStyle(item).borderWidth.replace("px", "") * 2;
w = w + b;
minGap = 16;
n = Math.floor(W / w);
function calc(n: number): [number, number] {
gap = (W - n * w) / (n + 1);
if (gap < minGap) {
n--;
gap = (W - n * w) / (n + 1);
return calc(n);
}
return [n, gap];
}
[n, gap] = calc(n);
console.log(`Put ${n} items in one row, gap is ${gap}px.`);
const halfGap = gap / 2;
container.style.paddingLeft = `${halfGap}px`;
container.style.paddingRight = `${halfGap}px`;
for (let item of container.children) {
(item as HTMLElement).style.marginLeft = `${halfGap}px`;
(item as HTMLElement).style.marginRight = `${halfGap}px`;
}
}useEffect(() => {
dynamicCalculate();
window.addEventListener("resize", dynamicCalculate);
return () => {
window.removeEventListener("resize", dynamicCalculate);
};
}, []);
return (Hello CodeSandbox
Start editing to see some magic happen!
{/* demo */}{Array.from({ length: 20 }).map((v, i) => {
return (Item-{i});
})});
}
codesandbox地址:demo在线预览
推荐阅读
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- 如何寻找情感问答App的分析切入点
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus使用queryWrapper如何实现复杂查询
- 如何在Mac中的文件选择框中打开系统隐藏文件夹
- 漫画初学者如何学习漫画背景的透视画法(这篇教程请收藏好了!)
- java中如何实现重建二叉树
- Linux下面如何查看tomcat已经使用多少线程
- thinkphp|thinkphp 3.2 如何调用第三方类库
- 2019女表什么牌子好(如何挑选女士手表?)