jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。获取文档高度是前端开发中常见的需求,通常用于页面滚动、动态加载内容等场景。
获取文档高度主要有以下几种方式:
$(document).height()
和 $(window).height()
返回的值不同?原因:
$(document).height()
返回的是整个文档的高度,包括不可见的部分(如滚动条区域)。$(window).height()
返回的是视口的高度,即浏览器窗口可见区域的高度。解决方法:
根据具体需求选择合适的方法。如果需要获取整个文档的高度,使用 $(document).height()
;如果需要获取视口的高度,使用 $(window).height()
。
原因:
解决方法:
$(window).on('load', function() { ... })
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Height Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="content">
<!-- 这里可以放置大量内容 -->
</div>
<script>
$(document).ready(function() {
var documentHeight = $(document).height();
var viewportHeight = $(window).height();
var scrollTop = $(window).scrollTop();
console.log("Document Height: " + documentHeight);
console.log("Viewport Height: " + viewportHeight);
console.log("Scroll Top: " + scrollTop);
});
</script>
</body>
</html>
通过上述代码,可以在页面加载完成后获取文档高度、视口高度和滚动条到顶部的距离,并在控制台中输出这些值。