【问题标题】:How to use throttle from underscore.js如何使用 underscore.js 中的油门
【发布时间】:2012-12-22 04:46:40
【问题描述】:

我想使用throttle from underscore.js,但我不知道如何在我的代码中实现它。

<script type="text/javascript"> 
    $(document).ready(function() {
        /* Scroll event handler */
        $(window).bind('scroll',function(e){
            parallaxScroll();
        });
    }); 

    /* Scroll the background layers */
    function parallaxScroll(){
        var scrolled = $(window).scrollTop();
        $('header').css('top',(0+(scrolled*1))+'px');
        $('#balken0').css('top',(-600+(scrolled*1))+'px');
        $('#balken1').css('top',(-1465+(scrolled*1))+'px');
        $('#balken2').css('top',(-2320+(scrolled*1))+'px');
    }
</script>

提前谢谢你!

【问题讨论】:

  • var throttled = _.throttle(parallaxScroll, 100); $(window).scroll(throttled); ?
  • 我对 jquery 很陌生:D
  • 嗯,这很好,你知道throttle 做了什么。
  • 好的,代码可以工作,但我不希望#balken 完全不动!我的问题是,在 Firefox 中效果很好,但 safari 不行!
  • @JustKidding 查看已接受的答案。stackoverflow.com/questions/8907373/…

标签: jquery underscore.js throttling


【解决方案1】:

您可以使用计时器来获得相同的结果。为一个函数 IMO 包含整个库是没有意义的。

试试这个:

$(document).ready(function() {
    var timer;

    /* Scroll event handler */
    $(window).bind('scroll', function(e) {
        clearTimeout(timer);
        timer = setTimeout(parallaxScroll, 100);
    });
}); 

这将确保滚动事件仅在滚动结束后触发视差函数,而不是为页面滚动的每个像素调用一次。

【讨论】:

  • 这成功了!但我已经提到它对我不起作用!我希望#balken 根本不动
  • this worked! but i already mentioned that it doesn't work for me! 什么?这没有意义。
  • 在我的问题下查看我的评论!好的,代码有效,但我不希望#balken 根本不动!我的问题是,在 Firefox 中效果很好,但 safari 不行!
猜你喜欢
  • 2016-12-11
  • 2021-12-13
  • 2021-06-26
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2022-11-07
相关资源
最近更新 更多