通过JS 判断页面是否有滚动条的简单方法

JavaScript012

通过JS 判断页面是否有滚动条的简单方法,第1张

判断是否有滚动条的方法

function hasScrollbar() {    

    return document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight)

}

一般情况下,使用 document.body.scrollHeight >window.innerHeight 就可以判断。

但是在 IE7,IE8 中 window.innerHeight 为 underfined,所以为了兼容 IE7、IE8,需要使用 document.documentElement.clientHeight 属性计算窗口高度。

if (document.documentElement.clientHeight < document.documentElement.offsetHeight-4) //减4是因为浏览器的边框是2像素, 否则会一直判断有滚动条 

{

    alert('有滚动条')  

}

else

{

    alert('没有') 

}