监听滚动事件, 判断页面是否触底
监听页面是否触底
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
<p>18</p>
<p>19</p>
<p>20</p>
<p>21</p>
<p>22</p>
<p>23</p>
<p>24</p>
<p>25</p>
<p>26</p>
<p>27</p>
<p>28</p>
<p>29</p>
<p>30</p>
<p>31</p>
<p>32</p>
<p>33</p>
<p>34</p>
<p>35</p>
<p>36</p>
<p>37</p>
<p>38</p>
<p>39</p>
<p>40</p>
<p>41</p>
<p>42</p>
<p>43</p>
<p>44</p>
<p>45</p>
<p>46</p>
<p>47</p>
<p>48</p>
<p>49</p>
<p>50</p>
</div>
<script>
let flag = false;
function handleScroll () {
let scrollTop = document.documentElement.scrollTop;
let screenHeight = window.innerHeight;
let scrollHeight = document.documentElement.scrollHeight;
if (screenHeight + scrollTop === scrollHeight) {
flag = true;
} else {
flag = false;
}
console.log('flag', flag);
}
window.addEventListener("scroll", handleScroll, true);
</script>
</body>
监听元素是否触底
- 参考文献 https://zhuanlan.zhihu.com/p/469415873?utm_id=0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#box {
height: 300px;
width: 300px;
overflow-y: auto;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<div id="box">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
<p>18</p>
<p>19</p>
<p>20</p>
</div>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<script>
let flag = false
function handleScroll (e) {
let element = document.getElementById('box')
let scrollTop = element.scrollTop;
let clientHeight = element.clientHeight;
let scrollHeight = element.scrollHeight;
console.log('scrollTop', scrollTop)
console.log('clientHeight', clientHeight)
console.log('scrollHeight', scrollHeight)
if (clientHeight + scrollTop === scrollHeight) {
flag = true;
} else {
flag = false;
}
console.log('flag', flag);
}
window.addEventListener("scroll", handleScroll, true);
</script>
</body>
</html>