实现说明
演示用的数据放在这几个模块级绑定中:list、report、overflows。
使用要点
document只存在于浏览器——Node 运行时没有现成的垫片。- 每一步打印都带着自己的标签:
overflow: $、scrollbar gap: $。
常见问题
「scrollWidth 探测内容溢出」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
const overflows = report.scrollWidth > report.clientWidth;
const list = document.querySelector('#feed');
代码示例
// offsetWidth/clientWidth/scrollWidth answer different questions:
// the border-box size, the visible box inside the borders, and the
// full content size the element can scroll through
const list = document.querySelector('#feed');
const report = {
offsetWidth: list.offsetWidth,
clientWidth: list.clientWidth,
scrollWidth: list.scrollWidth,
};
// Horizontal overflow exists exactly when the content is wider than
// the visible box — the check behind "is my layout broken" heuristics
const overflows = report.scrollWidth > report.clientWidth;
console.log(`overflow: ${overflows}`);
// A visible scrollbar shows up as the offsetWidth minus clientWidth gap
console.log(`scrollbar gap: ${report.offsetWidth - report.clientWidth}`);