简单理解并获取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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」