Why do you need to get the width of the scrollbar
Recently, when writing a full-screen popover component, when the popover appears, the body will be set overflow: hidden, but when the height of the page is larger than one screen, there will be a phenomenon of shaking, which is analyzed to be the reason of the scroll bar; To enhance the user experience, add the margin-left property to offset the scrollbar position after overflow: hidden by determining whether there is a scrollbar, so you need to calculate the scrollbar width.
The principle of
- Create two divs nested together
- The outer div is fixed width and overflow: Scroll
- Width of scroll bar = outer div offsetWidth- Inner div offsetWidth
The implementation code
/** * getScrollWidth() {const Scroll = document.createElement("div"); const scrollIn = document.createElement("div"); scroll.appendChild(scrollIn); scroll.style.width = "100px"; scroll.style.height = "50px"; scroll.style.overflow = "scroll"; scroll.style.marginLeft = "-100000px"; document.body.appendChild(scroll); const scrollInWidth = scrollIn.offsetWidth; const scrollWidth = scroll.offsetWidth; const tmp = setTimeout(() => { document.body.removeChild(scroll); clearTimeout(tmp); }, 10); return scrollWidth - scrollInWidth; }Copy the code