jquery獲取窗口高度的方法及判斷scroll滾動到底部

$(window).height()     獲取的是當前可視窗口的高度,也就是用戶能看到的窗口的高度,是不變的(在窗口大小不變的前提下)
$(document).height()  獲取的是窗口內文檔的高度,這個高度隨着文檔內容的高度改變而改變


當窗口滾動條滾到最低端時,$(document).height() == $(window).height() + $(window).scrollTop()。
當窗口內文檔高度不足瀏覽器窗口高度時,$(document).height()返回的是$(window).height()。

$("body").height()   如果body沒有border、margin的話,$("body").height()==$(document).height(),但是還是不建議使用這種方式去獲取文檔內容高度

PS:如果你發現$(window).height()值有問題,返回的不是瀏覽器窗口的高度,那麼看看是不是網頁沒有加上<!DOCTYPE>聲明


滾動某個div中內容的情形如下

代碼:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".btn1").click(function(){
    $("div").scrollTop(100);
  });
  $(".btn2").click(function(){
    alert($("div").scrollTop()+" px");
  });
});
</script>
</head>
<body>
<div style="border:1px solid black;width:200px;height:200px;overflow:auto">
This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.
</div>
<button class="btn1">把 scroll top offset 設置爲 100px</button>
<br />
<button class="btn2">獲得 scroll top offset</button>
</body>
</html>

當滾動條滾動到底部時,此時$("div").scrollTop() = 394px   $("div").height()爲div的高度200px不變

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章