700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JavaScript——获取浏览器滚动条(ScrollBar)宽度

JavaScript——获取浏览器滚动条(ScrollBar)宽度

时间:2021-05-22 18:18:28

相关推荐

JavaScript——获取浏览器滚动条(ScrollBar)宽度

问题描述

不同浏览器的滚动条宽度不相同,需要动态获取浏览器滚动条宽度。

问题分析

screen.width屏幕分辨率宽度

document.body.scrollWidth页面完整宽度

document.body.scrollHeight页面完整宽度

document.body.clientWidthwidth+左右padding

document.body.clientHeightheight + 上下padding

document.body.offsetWidth网页可见区域宽度

document.body.offsetHeight网页可见区域高度

body中插入一个div,div中再嵌套一个div,设置外部的div的overflower为scroll,

可以出现滚动条轨道,然后使用外部div宽度值减去内部div的宽度值即可。

得到滚动条宽度之后,把添加的元素删掉。

解决方案

方法一:简单方法

var cWidth = document.body.clientWidth || document.documentElement.clientWidth;//页面可视区域宽度var iWidth = window.innerWidth;//浏览器窗口大小console.log(iWidth - cWidth);//打印滚动条宽度

方法二:iView的解决方案

/iview/iview/blob/2.0/src/utils/assist.js

// For Modal scrollBar hiddenlet cached;export function getScrollBarSize (fresh) {if (isServer) return 0;if (fresh || cached === undefined) {const inner = document.createElement('div');inner.style.width = '100%';inner.style.height = '200px';const outer = document.createElement('div');const outerStyle = outer.style;outerStyle.position = 'absolute';outerStyle.top = 0;outerStyle.left = 0;outerStyle.pointerEvents = 'none';outerStyle.visibility = 'hidden';outerStyle.width = '200px';outerStyle.height = '150px';outerStyle.overflow = 'hidden';outer.appendChild(inner);document.body.appendChild(outer);const widthContained = inner.offsetWidth;outer.style.overflow = 'scroll';let widthScroll = inner.offsetWidth;if (widthContained === widthScroll) {widthScroll = outer.clientWidth;}document.body.removeChild(outer);cached = widthContained - widthScroll;}return cached;}

方法三:Element UI的解决方案

/ElemeFE/element/blob/dev/src/utils/scrollbar-width.js

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';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%';outer.appendChild(inner);const widthWithScroll = inner.offsetWidth;outer.parentNode.removeChild(outer);scrollBarWidth = widthNoScroll - widthWithScroll;return scrollBarWidth;};

参考文章

/53793.html

/q/1010000004817695

/wangch5453/blog/2967396

/qq_42089654/article/details/80515916

/MakethingsEasy/archive//12/08/2280661.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。