首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >计算滚动条的宽度–js

计算滚动条的宽度–js

作者头像
全栈程序员站长
发布2022-09-07 11:17:53
发布2022-09-07 11:17:53
13.2K0
举报

大家好,又见面了,我是你们的朋友全栈君。

原理

  1. 创建两个div嵌套在一起
  2. 外层的div设置固定宽度和overflow:scroll
  3. 滚动条的宽度=外层div的offsetWidth-内层div的offsetWidth

实现代码

代码语言:javascript
复制
/**
 * 获取滚动条的宽度
 */
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;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154675.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 原理
  • 实现代码
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档