关于手机端滚动加载更多多次触发事件问题

在做手机端滚动加载更多时,因为滚动是一个持续过程,所以就导致了会一次或很短时间内触发多次ajax请求,  可以设置一个全局变量控制.

// bool变量, 用于阻止滚动到底部连续触发多次

  let isBottom = true


const scrollHeight = element.currentTarget.scrollHeight
const scrollTop = element.currentTarget.scrollTop
// height - top - 容器高度
const scrollLength = scrollHeight - scrollTop
const liBottom = scrollLength - newsContainer
if (liBottom > 100 && liBottom < 180) {
  if (isBottom === true) {
    isBottom = false
    // $(ajax)
  }
}


然后取消false,百度很多都是设置延迟1秒种取消,我是用的滚动条高度

if (liBottom > 1000) {
      isBottom = true
    }



  // 视频模板
  const vTemple = (url, title, image, visit, catName) => {
    const res = `
  • 阅读量:${visit}    ${catName}
  • ` return res } // 无内容 const noTemple = () => { const res = '
  • 再怎么拉都没有啦,不如看看其他版块内容吧!
  • ' return res } // 分页 let currentPage = 1 // 分类id let categoryId = 0 // 用户id let userId = 0 // bool变量, 用于阻止滚动到底部连续触发多次 let isBottom = true const windowHeight = $(window).height() // 列表容器高度 const newsContainer = windowHeight - 120 // 设置容器高度 $('.mobile-main .m-news-list-tit').css('height', `${newsContainer}px`) // 滚动监听 $('.mobile-main .m-news-list-tit').on('scroll', (element) => { const scrollHeight = element.currentTarget.scrollHeight const scrollTop = element.currentTarget.scrollTop // height - top - 容器高度 const scrollLength = scrollHeight - scrollTop const liBottom = scrollLength - newsContainer if (liBottom > 100 && liBottom < 250) { if (isBottom === true) { // isBottom 为false 防止连续下拉加载多次 isBottom = false categoryId = $(element.currentTarget).find('#categoryId').val() userId = $(element.currentTarget).find('#userId').val() const nextPage = currentPage + 1 const ajaxOptions = { method: 'POST', data: { id: categoryId, user_id: userId, page: nextPage } } let articleList = '' $.ajax('xxxxxx', ajaxOptions).done((data) => { const articles = data.articles articles.forEach((article) => { let url = article.url if (article.url === '') { url = `/articles/${article.id}` } const title = article.title let image = article.image const visit = article.visit const catName = article.name articleList = vTemple(url, title, image, visit, catName) $(element.currentTarget).find('.articles-list-summary').append(articleList) }) if (articles.length > 0 && articles.length < 19) { articleList = noTemple() $(element.currentTarget).find('.articles-list-summary').append(articleList) } }).fail(() => { // no data }) // 下一页 currentPage = nextPage } } // 当滚动条高度变化后让isBottom为true if (liBottom > 1000) { isBottom = true } })

    你可能感兴趣的:(js)