Element分析(工具篇)——ScrollbarWidth

说明

用来获取滚动条宽度。

源码解析

import Vue from 'vue';

let scrollBarWidth;

export default function() {
  if (Vue.prototype.$isServer) return 0;  // 服务器端直接返回
  if (scrollBarWidth !== undefined) return scrollBarWidth;  // 如果已经计算过就直接返回之前的

  const outer = document.createElement('div');  // 创建外部的容器
  outer.className = 'el-scrollbar__wrap';  // 同样会加入overflow: scroll
  outer.style.visibility = 'hidden';  // 不可见
  outer.style.width = '100px';  // 设置一个宽度
  outer.style.position = 'absolute';  // 绝对定位
  outer.style.top = '-9999px';  // 移除可视区域
  document.body.appendChild(outer);  // 插入

  const widthNoScroll = outer.offsetWidth;  // 可是宽度
  outer.style.overflow = 'scroll';  // 会显示出滚动条

  const inner = document.createElement('div');  // 创建内部
  inner.style.width = '100%';  // 宽度为100%,实际上因为父级有滚动条,父级的 width 会变成 100px - 滚动条宽度
  outer.appendChild(inner);  // 插入

  const widthWithScroll = inner.offsetWidth;  // 内部宽度
  outer.parentNode.removeChild(outer);  // 移除

  return widthNoScroll - widthWithScroll;  // 滚动条宽度
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,687评论 1 92
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,243评论 4 61
  • HTML标签解释大全 一、HTML标记 标签:!DOCTYPE 说明:指定了 HTML 文档遵循的文档类型定义(D...
    米塔塔阅读 8,673评论 1 41
  • !~~~终于开始了在Coursera上的第一个编程练习 。。。 下面就是这次作业的介绍了~: Introducti...
    东皇Amrzs阅读 13,220评论 9 7
  • 1. Eat Thy Neighbour 只看封面设计就能知道内容的一本书。 “食人”是个吸引眼球的题材——很多t...
    一条污蚣阅读 4,053评论 0 0