1

我有这个代码:

$(window).scroll(function () {
    if ($(this).scrollTop() > ($animate.headline.height() + 100)) {
        $animate.header.velocity({height: "50px"}, { queue: false });
    } else {
        $animate.header.velocity({height: "100px"}, { queue: false });
    }
});

如果用户从顶部滚动 xxx 像素,则动画应该开始,并且效果很好。

我刚刚注意到的一件事让我很困扰 - 每次滚动时,速度动画都会检查 scrollTop,所以当我滚动时整体动画并不流畅,因为在触发动画之前,函数正在检查滚动。

有没有其他方法可以让它平滑?

例子:

http://codepen.io/anon/pen/bIkqF

4

2 回答 2

3

您更喜欢 CSS 方法吗?

将标题的 css 设置为:

-webkit-transition: all 0.5s;
position:fixed;
top:0;
left:0;

为所需高度添加一个新类:

.shrink{
    height:50px;
}

在你的 js 中切换类:

var header = $('.header');
  $(window).on('scroll', function () {
      if ($(this).scrollTop() > (header.height() + 20)) {
          header.addClass('shrink');
      } else {
          header.removeClass('shrink');
      }
  });

修改转场的 seconds 属性以获得更平滑的效果。

通过这种方式,GPU 完成了繁重的工作,并且类切换对性能的影响可以忽略不计。 演示

于 2014-09-15T14:42:06.930 回答
0

您应该使用像 Ben Alman 的一些库来限制您的检查: https ://raw.githubusercontent.com/cowboy/jquery-throttle-debounce/v1.1/jquery.ba-throttle-debounce.min.js 。

检查此文档页面:http ://benalman.com/projects/jquery-throttle-debounce-plugin/ 。

对于您的示例,您可以像这样使用它:

$(window).scroll($.throttle(250, checkTop));

function checkTop() {
    if ($(this).scrollTop() > ($animate.headline.height() + 100)) {
        $animate.header.velocity({height: "50px"}, { queue: false });
    } else {
        $animate.header.velocity({height: "100px"}, { queue: false });
    }
}
于 2014-09-15T14:21:16.170 回答