[英]Is there a way to check when a scroll bar appears in Javascript without using jquery?
我希望能够检测到垂直滚动条何时出现,但我不想使用 jQuery。 有没有办法在不使用 jQuery 的情况下做到这一点?
您可以检查元素的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>
当然,这不是最可靠的解决方案,因为您还需要检查元素的overflow-y
CSS 属性。 如果设置为scroll
,那么总会有一个滚动条,但如果设置为auto
,则需要检查scrollHeight
和clientHeight
。
const styles = window.getComputedStyle(elem);
const hasScrollBar = styles.overflowY === "scroll"
|| styles.overflowY === "auto" && elem.scrollHeight > elem.clientHeight;
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>
没有滚动条的例子:
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>
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.