總體思路就是往body中插入一個div,div中再嵌套一個div,設置外部的div的overflower爲scroll,javascript
這樣就能夠出現滾動條軌道,而後使用外部div寬度值減去內部div的寬度值便可了 。java
獲得滾動條寬度以後記得把添加的元素刪掉。app
詳細以下代碼code
const getScrollBarWidth = () => { const outer = document.createElement("div"); 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; };