Created
April 23, 2018 09:50
-
-
Save 337547038/baa0444f4bd94eb48a1b286c25986376 to your computer and use it in GitHub Desktop.
js获取滚动条的宽度
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
判断滚动条的需求在弹窗插件中使用比较多,当弹窗添加overflow: hidden时,如果页面比较长的话,添加这个属性之后页面会有晃动。 | |
为了增强用户体验,通过判断是否有滚动条而添加 margin-left 属性以抵消 overflow: hidden 之后的滚动条位置。 | |
判断是否有滚动条的方法 | |
function hasScrollbar() { | |
return document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight); | |
} | |
计算滚动条宽度的方法 | |
新建一个带有滚动条的 div 元素,通过该元素的 offsetWidth 和 clientWidth 的差值即可获得 | |
function getScrollbarWidth() { | |
var scrollDiv = document.createElement("div"); | |
scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;'; | |
document.body.appendChild(scrollDiv); | |
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; | |
document.body.removeChild(scrollDiv); | |
return scrollbarWidth; | |
} |
window.innerWidth - document.body.clientWidth
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
计算滚动条宽度的算法有误,ele.offsetWidth - ele.clientWidth 的结果应该是 (scrollBar + borderLeft + borderRight)的宽度。楼主的说法仅在border为0时正确。:)