2013-05-09 69 views
2

我知道這個問題已被問到ad nauseum,但我很難過,因爲嘗試了幾種不同的解決方案後,我仍然無法讓我的腳本正確檢測滾動條。javascript檢測滾動條不工作

這是我目前正在使用,以試圖發現一個滾動條功能:

function checkScrollBar() { 
    var hContent = $("body").height(); // get the height of your content 
    var hWindow = $(window).height(); // get the height of the visitor's browser window 

    if(hContent>hWindow) { // if the height of your content is bigger than the height of the browser window, we have a scroll bar 
    return true;  
    } 

    return false; 
} 

的問題是,即使我的網頁上有名副其實的垂直滾動條彈出,因爲頁面的內容比筆記本電腦上的窗口更長,此功能仍然表示窗口高度等於身高。

我對JavaScript/jQuery還是比較新的,所以如果我錯過了一個重大錯誤,請保持溫柔。

+3

正與'document'取代'body'! – adeneo 2013-05-09 16:53:49

+0

@adeneo太棒了!太棒了。我想知道爲什麼身體不起作用? – jcsbrotha 2013-05-09 16:57:51

+0

@jcsbrotha你不能直接選擇正文標籤。最好選擇文檔標籤。 – Kivylius 2013-05-09 16:58:36

回答

1

您需要考慮頁面的偏移量。

function checkScrollBar() { 
    var hContent = $(document).height(); // get the height of your content 
    var hWindow = $(window).height(); // get the height of the visitor's browser window 

    if(hContent>hWindow) { // if the height of your content is bigger than the height of the browser window, we have a scroll bar 
    return true;  
    } 

    return false; 
} 

實施例:http://jsfiddle.net/a2rnd/

+1

謝謝你的回答! – jcsbrotha 2013-05-09 16:58:08

+1

如果你無法從興奮中分辨出來,它就會奏效。 – jcsbrotha 2013-05-09 16:58:24

+0

@jcsbrotha如果我的問題是正確的,請點擊滴答聲向上/下降,謝謝。 – Kivylius 2013-05-09 18:50:05

0

爲它一點插件。

(function($) { 
    $.fn.hasScrollBar = function() { 
     return this.get(0).scrollHeight > this.height(); 
    } 
})(jQuery); 

這樣使用它,

$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise.. 

DEMO

測試的火狐,Chrome,IE6,7,8