【JS】各浏览器滚动条默认宽度是多少?

现在各大浏览器滚动条的默认宽度是多少呢?有没有什么接口可以快速获取其宽度呢?

回答

我记得也是17px

window.innerWidth - document.body.clientWidth //火狐下17px IE11下17px

chrome的滚动条 我给关了 所以没测试
window.innerWidth 浏览器可用宽度
document.body.clientWidth body的宽度
我这个式子是在body没有marginpaddingborder的情况下得到的
如果你要是有的话可以做减法

//margin

document.body.style.marginLeft

document.body.style.marginRight

//padding

document.body.style.paddingLeft

document.body.style.paddingRight

//border

document.body.style.borderLeft

document.body.style.borderRight

另外科普一下:
screen.width屏幕分辨率宽度
document.body.scrollWidth 页面完整宽度
document.body.scrollHeight 页面完整宽度
document.body.offsetWidth 网页可见区域宽度
document.body.offsetHeight 网页可见区域高度

用兩層 div
外層先設定 overflow: scroll,量取內層 div 寬度
再將外層 div 設定 overflow: hidden,再量內層 div 寬度

兩個寬度差就是 scrollbar 的寬度

https://jsfiddle.net/fdamw8sb/


或是直接用 offsetWidthclientWidth 的差值也能算出來
ref: https://davidwalsh.name/detect-scrollbar-width

// Create the measurement node

var scrollDiv = document.createElement("div");

scrollDiv.style.overflow = 'scroll';

document.body.appendChild(scrollDiv);

// Get the scrollbar width

var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;

console.warn(scrollbarWidth); // Mac: 15

// Delete the DIV

document.body.removeChild(scrollDiv);

【JS】各浏览器滚动条默认宽度是多少?

默认滚动条不记在body中

在20px左右

我记得是17px

得自己量量,有时候更新一次版本换一次

var cWidth = document.body.clientWidth || document.documentElement.clientWidth;//页面可视区域宽度

var iWidth = window.innerWidth;//浏览器窗口大小

console.log(iWidth - cWidth);//打印滚动条宽度

在body无border-width的情况下
window.innerWidth - document.body.clientWidth

刚才在看源码,搬运一下代码 https://github.com/iview/ivie...

// 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;

}

不同操作系统和浏览器,滚动条都是不同宽度的,可以看这篇文章《滑向未来(现代 JavaScript 与 CSS 滚动实现指南)》。

以上是 【JS】各浏览器滚动条默认宽度是多少? 的全部内容, 来源链接: utcz.com/a/85646.html

回到顶部