zoukankan      html  css  js  c++  java
  • 监听页面滚动防抖,以及节流

    //1.与router文件并列新建一个utils/unils.js,在里面编写页面防抖方法
     // 用于存储工具方法
    export default {
    debounce (fn, wait, time) {
        var previous = null // 记录上一次运行的时间
        var timer = null
        return function () {
          var now = +new Date()
          if (!previous) previous = now
          // 当上一次执行的时间与当前的时间差大于设置的执行间隔时长的话,就主动执行一次
          if (now - previous > time) {
            clearTimeout(timer)
            fn()
            previous = now // 执行函数后,马上记录当前时间
          } else { // 否则重新开始新一轮的计时
            clearTimeout(timer)
            timer = setTimeout(function () {
              fn()
            }, wait)
          }
        }
      },
      throttle (fn, time) {
        let _self = fn
        let timer = ''
        let firstTime = true // 记录是否是第一次执行的flag
    
        return function () {
          let args = arguments // 解决闭包传参问题
          let _me = this // 解决上下文丢失问题
    
          if (firstTime) { // 若是第一次,则直接执行
            _self.apply(_me, args)
            firstTime = false
            return
          }
          if (timer) { // 定时器存在,说明有事件监听器在执行,直接返回
            return false
          }
    
          timer = setTimeout(function () {
            clearTimeout(timer)
            timer = null
            _self.apply(_me, args)
          }, time || 500)
        }
      },
    }
    

      //2.在页面调用 

       

     // 监听页面滚动防抖
     this.addEvent(document, 'scroll', this.$utils.debounce(this.tableScroll, 100))
     // 输入搜索节流  [左侧栏输入搜索]
     let searchOrgan = document.getElementById('searchOrgan') //获取搜索框
      this.addEvent(searchOrgan, 'keyup', this.$utils.throttle(this.searchOrganEven, 300))
    

      

  • 相关阅读:
    [HNOI2002]营业额统计
    HDU 1374
    HDU 3345
    HDU 2089
    Graham扫描法
    Codeforces 1144D Deduction Queries 并查集
    Codeforces 916E Jamie and Tree 线段树
    Codeforces 1167F Scalar Queries 树状数组
    Codeforces 1167E Range Deleting
    Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望
  • 原文地址:https://www.cnblogs.com/cyf-1314/p/13739799.html
Copyright © 2011-2022 走看看