节流javascript功能

时间:2018-03-15 02:10:24

标签: javascript jquery scroll scrolltop

我有一些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>

我尝试了一些变化,但我无法解决问题所在,是否有人知道如何将此事件限制在30ms左右?

2 个答案:

答案 0 :(得分:0)

尝试以下代码适合您。如果您的浏览器不支持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)
    }
  }
}

答案 1 :(得分:0)

工作答案:

<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>
相关问题