简单理解并获取js中常用的高度

获取 节点 距离 父元素的高度

// 返回页面到 父元素 的距离 , 若距离为 0 ,则去返回 到body的距离
div.offsetTop
$('div').offset().top

 // 返回页面到顶部(body )的距离
div.getBoundingClientRect().top

 

获取 节点 的滚动的高度 (滚动条距离顶部的高度)

$(window).scrollTop(); 
window.scrollY

获取 节点 的窗口高度 (当前可见区域大小)

$(window).height()
document.documentElement.clientHeight

获取 节点 的文档总高度 (页面总高度) 

$(document).height()
document.body.clientHeight

因此可总结出: 滚动的高度 + 页面窗口高度 <= 文档文本高度

 

小结:

1.当浏览器窗口大小改变时(如最大化或拉大窗口) ,$(window).height() 随之改变,但是$(document).height()是不变的。

2.当页面缩放百分比变化时,两个高度都会变,但不影响判断滚动条是否到底部,下面两个则不会受到页面百分比缩放影响

屏幕分辨率的高:         window.screen.height;          // 1085
屏幕可用工作区高度: window.screen.availHeight;   //  1045  即去掉收藏夹输入栏那一块的高度

 

使用例子:

判断滚动条是否滑到最底部,引用网上的demo

jq写法

$(window).scroll(function(){
  
    var scrollTop = $(window).scrollTop();
    var scrollHeight = $(document).height();
    var windowHeight = $(window).height();

    if(scrollTop + windowHeight == scrollHeight){
        console.log("已经到最底部了!");
    }
});

js写法

    window.onscroll = function(){
        if(getScrollTop() + getWindowHeight() == getScrollHeight()){
            alert("已经到最底部了!!");
        }
    };

// 滑动高度
function getScrollTop(){
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if(document.body){
        bodyScrollTop = document.body.scrollTop;
    }
    if(document.documentElement){
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

//文档的总高度
function getScrollHeight(){
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if(document.body){
        bodyScrollHeight = document.body.scrollHeight;
    }
    if(document.documentElement){
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}
// 屏幕高度
function getWindowHeight(){
    var windowHeight = 0;
    if(document.compatMode == "CSS1Compat"){
        windowHeight = document.documentElement.clientHeight;
    }else{
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}
posted @ 2022-05-05 20:17  jaychou、  阅读(224)  评论(0编辑  收藏  举报