2025年计算滚动条的宽度–js

计算滚动条的宽度–js原理 创建两个 div 嵌套在一起 外层的 div 设置固定宽度和 overflow scroll 滚动条的宽度 外层 div 的 offsetWidth 内层 div 的 offsetWidth 实现代码 获取滚动条的宽度 getScrollWid const scroll document createElemen div const scrollIn

原理

创建两个div嵌套在一起

外层的div设置固定宽度和overflow:scroll

滚动条的宽度=外层div的offsetWidth-内层div的offsetWidth

实现代码

/**
* 获取滚动条的宽度
*/
getScrollWidth() {
const scroll = document.createElement("div");
const scrollIn = document.createElement("div");
scroll.appendChild(scrollIn);
scroll.style.width = "100px";
scroll.style.height = "50px";
scroll.style.overflow = "scroll";
scroll.style.marginLeft = "-100000px";
document.body.appendChild(scroll);
const scrollInWidth = scrollIn.offsetWidth;
const scrollWidth = scroll.offsetWidth;
const tmp = setTimeout(() => {
document.body.removeChild(scroll);
clearTimeout(tmp);
}, 10);
return scrollWidth - scrollInWidth;
}
编程小号
上一篇 2025-02-28 18:57
下一篇 2025-03-07 11:46

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/118075.html