您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用JavaScript获取滚动条的宽度

使用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;

}

基本步骤如下:

如果在Windows(metro)应用程序上使用此功能,请确保将“外部” div 的-ms-overflow- style属性设置为scrollbar,否则将无法正确检测到宽度。(代码已更新)

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

javascript 2022/1/1 18:21:30 有299人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶