Jquery中用offset().top和offsetTop的比較

今天,想測試一個div與頂部的距離,用的是.offsetTop,可是offsetTop得到的值,怎麼都打印不出來。折騰了半天,打印的結果都是undefined,雖然網上不少資料都說返回的是數值。雖然這個函數永不了,可是黃顯欽找到了一個能夠替代offsetTop的函數。那就是jquery的offset().topjavascript

 

咱們先來了解一下,什麼是offset().top和offsetTop?css

 

offsetTophtml

解析一:java

假設 obj 爲某個 HTML 控件。jquery

obj.offsetTop 指 obj 相對於版面或由 offsetParent 屬性指定的父座標的計算上側位置,整型,單位像素。瀏覽器

解析二: ide

當前對象到其上級層頂部的距離.函數

不能對其進行賦值.設置對象到頁面頂部的距離請用style.top屬性.測試

 

這是從網上找到的兩種解析,您看着用,我也沒搞懂,主要是打印不出offsetTop來。spa

 

 

若是須要獲取當前元素到document的高度,建議使用jquery的offset().top。下面咱們解析一下offset().top。

 offset().top

offset()的top是指元素與document的上邊的距離,而不是瀏覽器當前窗體的上邊緣,如圖1。

 圖1:document高度超過window,瀏覽器出現滾動條,滾動滾動條,提交按鈕的offset不變。

技術分享

 

圖2:document中的div有滾動條,提交按鈕的offset隨div的滾動變化而變化,與document無關

技術分享

 

從上面這兩個圖,咱們就知道jquery的offset.top的用法區別了。

實例一:判斷DIV什麼時候出現

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>js</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).scroll(function () {
    var a = document.getElementById("eq").offsetTop;
    console.log("offsetTop:",a);

    var b = $(window).scrollTop();
    var c = $(window).scrollTop()+$(window).height();
    console.log("window.scrollTop:",b);
    if (c >= a) {
        console.log("----",a,c);
    }
});
});
</script>
</head>
<body>
<div style="width:1px;height:2000px;"></div>
<div id="eq" style=" width:100px; height:100px; background-color:Red;">1</div>
<div style="width:1px;height:2000px;"></div>
</body>
</html>

 實例二:

相似豆瓣主頁的熱門活動,當滾動到那的時候一直在頂部

//返回頂部
        $('.toTopShortBtn').hide();
        var back = $('.toTopShortBtn a');
        back.click(function() {
            var timer = setInterval(function(){
                $(window).scrollTop($(window).scrollTop()-50);
                if($(window).scrollTop() == 0){
                    clearInterval(timer);
                }
            },2);
        });
        var a = $(".hothuodong").offset().top;
        $(window).scroll( function() {
            if($(window).scrollTop() > 400){
                $('.toTopShortBtn').show();
            }else{
                $('.toTopShortBtn').hide();
            }

            var b = $(window).scrollTop();
            if (b >= a) {
                $(".hothuodong").css('position','fixed');
            }else{
                $(".hothuodong").css('position','static');
            }
        });
相關文章
相關標籤/搜索