簡體   English   中英

有沒有辦法在不使用 jquery 的情況下檢查 Javascript 中何時出現滾動條?

[英]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 ,則需要檢查scrollHeightclientHeight

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM