栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JavaScript获取滚动条的宽度

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JavaScript获取滚动条的宽度

此功能应为您提供滚动条的宽度

function getScrollbarWidth() {  // Creating invisible container  const outer = document.createElement('div');  outer.style.visibility = 'hidden';  outer.style.overflow = 'scroll'; // forcing scrollbar to appear  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps  document.body.appendChild(outer);  // Creating inner element and placing it in the container  const inner = document.createElement('div');  outer.appendChild(inner);  // Calculating difference between container's full width and the child width  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);  // Removing temporary elements from the DOM  outer.parentNode.removeChild(outer);  return scrollbarWidth;}

基本步骤如下:

  1. 创建隐藏的div(外部)并获取其偏移宽度
  2. 使用CSS溢出属性强制滚动条显示在div(外部)中
  3. 创建新的div(内部)并附加到外部,将其宽度设置为“ 100%”并获得偏移宽度
  4. 根据收集的偏移量计算滚动条宽度

更新资料

如果在Windows(metro)应用程序上使用此功能,请确保将“外部” div 的-ms-overflow-
style属性设置为

scrollbar
,否则将无法正确检测到宽度。(代码已更新)

更新#2 在默认设置为“仅在滚动时显示滚动条”(Yosemite及更高版本)的Mac OS上,这将不起作用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415946.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号