效果图:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>JS滚动条位置,顶部,底部,触发事件</title></head><body><style>body {margin: 0;padding: 0;height: 200vh;}</style><script>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;}console.log("被卷曲的头",document.body.scrollTop,document.documentElement.scrollTop);function getWindowHeight() {var windowHeight = 0;if (document.compatMode == "CSS1Compat") {windowHeight = document.documentElement.clientHeight;} else {windowHeight = document.body.clientHeight;}return windowHeight;}console.log("客户端可视区域高度",document.body.clientHeight,document.documentElement.clientHeight);// 文档的总高度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;}console.log("文档总高度",document.body.scrollHeight,document.documentElement.scrollHeight);window.onscroll = function() {if (getScrollTop() == 0) {console.log("顶部");}if (getScrollTop() + getWindowHeight() == getScrollHeight()) {console.log("已经到最底部了!!");}};</script></body>
</html>