javascript
JavaScript——获取浏览器滚动条(ScrollBar)宽度
問題描述
不同瀏覽器的滾動條寬度不相同,需要動態獲取瀏覽器滾動條寬度。
問題分析?
screen.width屏幕分辨率寬度
document.body.scrollWidth?頁面完整寬度
document.body.scrollHeight?頁面完整寬度
document.body.clientWidth?width+左右padding
document.body.clientHeight?height + 上下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的解決方案?
https://github.com/iview/iview/blob/2.0/src/utils/assist.js
// For Modal scrollBar hidden let 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的解決方案
https://github.com/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; };參考文章
http://www.caotama.com/53793.html
https://segmentfault.com/q/1010000004817695
https://my.oschina.net/wangch5453/blog/2967396
https://blog.csdn.net/qq_42089654/article/details/80515916
https://www.cnblogs.com/MakethingsEasy/archive/2011/12/08/2280661.html
總結
以上是生活随笔為你收集整理的JavaScript——获取浏览器滚动条(ScrollBar)宽度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML/CSS——子元素相对于父元素固
- 下一篇: Vue——props默认值为工厂函数时[