简体   繁体   English

有没有办法在不使用 jquery 的情况下检查 Javascript 中何时出现滚动条?

[英]Is there a way to check when a scroll bar appears in Javascript without using jquery?

I would like to be able to detect when the vertical scroll bar appears but i don't want to use jQuery.我希望能够检测到垂直滚动条何时出现,但我不想使用 jQuery。 Is there some way to do this without using jQuery?有没有办法在不使用 jQuery 的情况下做到这一点?

You can check if the element's scrollHeight is greater than its clientHeight .您可以检查元素的scrollHeight是否大于其clientHeight

const hasScrollBar = elem.scrollHeight > elem.clientHeight;

 const div = document.querySelector("div"); const hasScrollBar = div.scrollHeight > div.clientHeight; console.log(hasScrollBar);
 <div style="max-height: 100px; border: 1px solid blue; overflow: auto;"> <p>Stuff</p> <p>Stuff</p> <p>Stuff</p> <p>Stuff</p> <p>Stuff</p> <p>Stuff</p> <p>Stuff</p> </div>

Of course, this is not the most robust solution, as you will also want to check the overflow-y CSS property of the element.当然,这不是最可靠的解决方案,因为您还需要检查元素的overflow-y CSS 属性。 If it is set to scroll , then there is always a scrollbar, but if it is set to auto , then the scrollHeight and clientHeight will need to be checked.如果设置为scroll ,那么总会有一个滚动条,但如果设置为auto ,则需要检查scrollHeightclientHeight

const styles = window.getComputedStyle(elem);
const hasScrollBar = styles.overflowY === "scroll" 
            || styles.overflowY === "auto" && elem.scrollHeight > elem.clientHeight;

Example with overflow: scroll : overflow: scroll

 const elem = document.querySelector("div"); const styles = window.getComputedStyle(elem); const hasScrollBar = styles.overflowY === "scroll" || styles.overflowY === "auto" && elem.scrollHeight > elem.clientHeight; console.log(hasScrollBar);
 <div style="height: 100px; overflow: scroll; border: 1px solid black;"></div>

Example without scrollbar:没有滚动条的例子:

 const elem = document.querySelector('div'); const styles = window.getComputedStyle(elem); const hasScrollBar = styles.overflowY === "scroll" || styles.overflowY === "auto" && elem.scrollHeight > elem.clientHeight; console.log(hasScrollBar);
 <div style="height: 300px; border: 1px solid black;"></div>

Example with document.scrollingElement : document.scrollingElement示例:

 const elem = document.scrollingElement; const hasScrollBar = elem.scrollHeight > elem.clientHeight; console.log(hasScrollBar);
 <p style="margin-top: 500px;">Bottom</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM