我有这个代码:
$(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
您更喜欢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');
}
});
使用过渡的秒属性进行微调,以获得更平滑的效果。
通过这种方式,GPU完成了繁重的任务,类切换的性能打击可以忽略不计。演示
您应该使用类似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 });
}
}