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

今天,想测试一个div与顶部的距离,用的是.offsetTop,但是offsetTop获得的值,怎么都打印不出来。折腾了半天,打印的结果都是undefined,虽然网上很多资料都说返回的是数值。虽然这个函数永不了,但是黄显钦找到了一个可以替代offsetTop的函数。那就是jquery的offset().top

我们先来了解一下,什么是offset().top和offsetTop?

offsetTop

解析一:

假设 obj 为某个 HTML 控件。

obj.offsetTop 指 obj 相对于版面或由 offsetParent 属性指定的父坐标的计算上侧位置,整型,单位像素。

解析二: 

当前对象到其上级层顶部的距离.

不能对其进行赋值.设置对象到页面顶部的距离请用style.top属性.

这是从网上找到的两种解析,您看着用,我也没搞懂,主要是打印不出offsetTop来。

如果需要获取当前元素到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="1px;height:2000px;"></div>
<div id="eq" style=" 100px; height:100px; background-color:Red;">1</div>
<div style="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');
            }
        });
原文地址:https://www.cnblogs.com/as3lib/p/6789647.html