[英]Why does offsetWidth show incorrect value?
我寫了這段代碼。
當我添加滾動條時,我得到 403 作為 clientWidth,這似乎是正確的:403px 用於內部內容 + 17px 用於滾動條。 然后我得到 403 作為 offsetWidth,但 offsetWidth 必須包括滾動條寬度。 因此我應該得到 403+17,而不是 403。
為什么我在 (*) 中得到 403?
let html = document.documentElement console.log(window.innerWidth) // 420 on my test console.log(html.clientWidth) // 420 console.log(html.offsetWidth) // 420 html.style.overflowY = 'scroll' // add scroll-bar console.log('Window: ' + window.innerWidth) // Window: 420 console.log('clientWidth: ' + html.clientWidth) // clientWidth: 403 console.log('offsetWidth: ' + html.offsetWidth) // offsetWidth: 403 (*)
你差點搞定我們! 但它是...
仔細看看documentElement
。
不包括滾動條! 因此,獲取包括滾動條在內的站點寬度的唯一方法是window.innerWidth
。
只讀Window屬性
innerWidth
返回窗口的內部寬度(以像素為單位)。 這包括垂直滾動條的寬度(如果存在)。
offsetWidth
的值將包括除documentElement
之外的所有元素的滾動條。offsetWidth
的documentElement
包括滾動條,但它根本沒有任何。 這意味着offsetWidth
和clientWidth
是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.