防抖节流事件
1.解决输入框输入不断发送请求(防抖)
onChange(e) {
if (timer) clearTimeout(timer)
if (e.detail.length === 0) {
this.setData({
keyword: "",
showFlag: 1
})
return;
} else {
this.setData({
keyword: e.detail
})
}
timer = setTimeout(() => {
getKeywordListData(e.detail).then(res => {
if (res.errno === 0) {
this.setData({
showFlag: 2,
keywordList: res.data
})
}
})
}, 200)
}
2.图片的下拉加载(节流)
//用来判断滚动条到底部的三个函数
//获取滚动条当前的位置
function getScrollTop() {
var scrollTop = 0;
if(document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if(document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
//获取当前可视范围的高度
function getClientHeight() {
var clientHeight = 0;
if(document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
} else {
clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
}
return clientHeight;
}
//获取文档完整的高度
function getScrollHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
scrollFn() {
// 滚动就执行这里的代码频繁触发事件
console.log(getClientHeight() + getScrollTop() == getScrollHeight() + 1);
// console.log("页面正在滚动");
// 如果滚动到底部的时候,
// if (到底部了) {
// if (窗口高度+scrollTop>=页面文档高度-20) {
if (getClientHeight() + getScrollTop() >= getScrollHeight() - 20) {
// 需要this.isLoading为false才能进行加载
if (!this.isLoading) {
// this.isLoading避免了重复触发这个到底了加载数据事件
this.page++;
this.isLoading = true;
setTimeout(() => {
// 往goodsListShow这个数组去push下一页的数据
// 从goodsList数组中去 this.page页的数据 push到goodsListShow
for (var i = this.size * (this.page - 1);i < this.size * this.page;i++) {
//this.goodsList[i]必须有这个值,才能push到展示的数组里面去
this.goodsList[i]
? this.goodsListShow.push(this.goodsList[i])
: "";
}
this.isLoading = false;
}, 500);
}
}