【问题标题】:Throttle javascript function节流 javascript 函数
【发布时间】:2018-03-15 02:10:23
【问题描述】:

我有一些 javascript 代码,当用户向上或向下滚动经过特定元素 (.closemenu) 时会触发点击事件。当用户滚动页面时,我使用它来自动打开和关闭标题菜单。

我遇到的问题是它触发了太多次并导致滚动时出现滞后和故障,我发现 this post 显示了滚动事件的节流用法,但我无法让它与我的当前的javascript是:

<script>
jQuery(window).scroll(function() {
   var hT = jQuery('.closemenu').offset().top,
       hH = jQuery('.closemenu').outerHeight(),
       wH = jQuery(window).height(),
       wS = jQuery(this).scrollTop();
    console.log((hT-wH) , wS);
   if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
   jQuery('.menu-bar').trigger('click');
   }
});
</script>

我已经尝试了一些变化,但我无法解决问题所在,有谁知道我怎样才能将这个事件限制在 30 毫秒左右?

【问题讨论】:

    标签: javascript jquery scroll scrolltop


    【解决方案1】:

    试试下面的代码是否适合你。如果您的浏览器不支持 ES6,您可以将 ES6 油门功能更改为 ES5。

    var func = function(){
        var hT = jQuery('.closemenu').offset().top,
           hH = jQuery('.closemenu').outerHeight(),
           wH = jQuery(window).height(),
           wS = jQuery(this).scrollTop();
        console.log((hT-wH) , wS);
       if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
       jQuery('.menu-bar').trigger('click');
       }
    }
    jQuery(window).scroll(function() {
      throttle(func,30);
    });
    
    
    const throttle = (func, limit) => {
      let inThrottle
      return function() {
        const args = arguments
        const context = this
        if (!inThrottle) {
          func.apply(context, args)
          inThrottle = true
          setTimeout(() => inThrottle = false, limit)
        }
      }
    }

    【讨论】:

      【解决方案2】:

      有效答案:

      <script>
      jQuery(window).scroll(function() {
         var hT = jQuery('.closemenu').offset().top,
             hH = jQuery('.closemenu').outerHeight(),
             wH = jQuery(window).height(),
             wS = jQuery(this).scrollTop();
          console.log((hT-wH) , wS);
         if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
         jQuery('.menu-bar').trigger('click');
         }
      
      function throttle(fn, threshhold, scope) {
        threshhold || (threshhold = 1250);
        var last,
            deferTimer;
        return function () {
          var context = scope || this;
      
          var now = +new Date,
              args = arguments;
          if (last && now < last + threshhold) {
            // hold on to it
            clearTimeout(deferTimer);
            deferTimer = setTimeout(function () {
              last = now;
              fn.apply(context, args);
            }, threshhold);
          } else {
            last = now;
            fn.apply(context, args);
          }
        };
      }
      
      });
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        • 2018-01-09
        • 2020-02-13
        • 2017-02-02
        相关资源
        最近更新 更多