一、需求
Html网页,下拉事件,下拉到底就加载数据,不断下拉不断出数据。
二、实现关键代码介绍
1.onscroll 事件在元素滚动条在滚动时触发。
https://www.runoob.com/jsref/event-onscroll.html
2.滚动条滚动时,距离顶部的距离
document.documentElement.scrollTop || document.body.scrollTop;
3可视区的高度
document.documentElement.clientHeight || document.body.clientHeight;
- 页面的总高度
document.documentElement.scrollHeight || document.body.scrollHeight;
三、实训案例(以Vue做案例)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div v-html="html"></div>
</div>
<script>
var vm = new Vue({
el: "#app",//挂载在app1上
data: {
html:"<div>\n" +
" <div style=\"background-color: cyan;height: 35vh\"></div>\n" +
" <div style=\"background-color: red;height: 35vh\"></div>\n" +
" <div style=\"background-color: chartreuse;height: 35vh\"></div>\n" +
" </div>",
//是否加载
isExecute:true
},
methods: {
//获取分享页面课程详情
getData: function () {
let that = this;
that.html += that.html;
//加载完了,放行下拉事件
that.isExecute = true
console.log(that.isExecute)
},
scroll() {
let that = this;
let beforeNum = 0;
window.onscroll = function(){
// scrollTop 滚动条滚动时,距离顶部的距离
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// windowHeight 可视区的高度
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
// scrollHeight 页面的总高度
var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 判断是否在下拉
if(scrollTop + windowHeight>beforeNum){
beforeNum = scrollTop + windowHeight;
// 滚动条到底部的条件
if(scrollTop + windowHeight > scrollHeight-20){
// console.log("加载数据")
// 是否加载数据避免方法重复执行
if(that.isExecute){
console.log("加载数据")
that.isExecute = false;
that.getData()
}
}
}else{
beforeNum = scrollTop + windowHeight;
}
}
},
},
mounted() {
this.scroll()
}
})
</script>
</body>
</html>