首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Throttle javascript函数

Throttle javascript函数
EN

Stack Overflow用户
提问于 2018-03-15 10:10:24
回答 2查看 763关注 0票数 0

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

我遇到的问题是,这会触发太多次,并导致滚动上的延迟和故障,我找到了this post,它显示了滚动事件的节流用法,但我无法让它与我当前的javascript一起工作,这是:

代码语言: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左右吗?

EN

回答 2

Stack Overflow用户

发布于 2018-03-15 10:19:14

如果下面的代码对您有效,请尝试。如果您的浏览器不支持ES6,您可以将ES6调节函数更改为ES5。

代码语言:javascript
复制
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)
    }
  }
}

票数 0
EN

Stack Overflow用户

发布于 2018-03-15 11:27:39

工作答案:

代码语言: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');
   }

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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49290474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档