【问题标题】:Animate element on user scroll用户滚动上的动画元素
【发布时间】:2017-07-12 21:08:37
【问题描述】:

我目前正在使用下面的逻辑来为导航块设置动画。当用户滚动大于 5px 时,它运行良好,元素动画出视口。但是,用户必须滚动窗口顶部才能使元素动画回原位。

如何在用户向上滚动时立即触发动画功能,而不是等待用户滚动到页面顶部? (不要等到他们到达页面顶部)

    var _throttleTimer = null;
    var _throttleDelay = 100;
    var $window = $(window);
    var $document = $(document);

    $document.ready(function () {

        $window
            .off('scroll', ScrollHandler)
            .on('scroll', ScrollHandler);

    });

    function ScrollHandler(e) {
        clearTimeout(_throttleTimer);
        _throttleTimer = setTimeout(function () {
            //console.log('scroll');

            if($(window).scrollTop() > 5) {
                $( ".mobile_header .content" ).animate({
                    top: "-34px"
                  }, 100 );
            } else {
                ////Need help here
                $( ".mobile_header .content" ).animate({
                    top: "34px"
                  }, 100 ); 
            }

    }, _throttleDelay);
}

【问题讨论】:

    标签: javascript if-statement scroll jquery-animate scrolltop


    【解决方案1】:

    这就是解决方案。必须修改逻辑来检测用户是向下滚动还是向上滚动。

    var _throttleTimer = null;
    var _throttleDelay = 100;
    var lastScrollTop = 0;
    var $window = $(window);
    var $document = $(document);
    
    $document.ready(function () {
        $window
         .off('scroll', ScrollHandler)
         .on('scroll', ScrollHandler);
    });
    
    function ScrollHandler(e) { 
        clearTimeout(_throttleTimer); 
        _throttleTimer = setTimeout(function () { 
            console.log('scroll');
    
            var st = $(this).scrollTop(); 
    
            if (st > lastScrollTop && $(window).scrollTop() > 5){ 
                $( ".mobile_header .content" ).animate({ 
                    top: "-34px" 
                }, 100 ); 
            } else { 
                $( ".mobile_header .content" ).animate({ 
                    top: "34px" 
                }, 100 ); 
            } 
    
            lastScrollTop = st; 
        }, _throttleDelay); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-08
      • 2015-09-03
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      相关资源
      最近更新 更多