我想要我的页眉缩小效果,加载的内容放大,滚动时缩小。
我所做的是通过 transform: scale(1.4) 增加大小,在滚动时我根据 scrollTop 和标题高度计算一个百分比,然后将它乘以 0.4。问题是滚动时屏幕开始振动,比例不平滑。您知道我的代码有什么问题吗?或者您能告诉我实现此目的的最佳做法是什么吗?
jQuery(document).ready(function(){
function zoom_out() {
var page_header_height = jQuery('#page-header-custom').outerHeight();
var scroll_top = jQuery(window).scrollTop();
var zoom_multiplier = 0.4;
var multiplier = (zoom_multiplier*(1-((scroll_top-jQuery('#page-header-custom').offset().top)/page_header_height))) > 1 ? 1 : (zoom_multiplier*(1-((scroll_top-jQuery('#page-header-custom').offset().top)/page_header_height)));
if(multiplier <= 1) {
jQuery('#page-header-inner').stop(true, true).transition({ scale: 1/(1+multiplier), translate: '0, -50%' });
jQuery('#page-header-custom').stop(true, true).transition({
scale: 1+multiplier
});
}
}
zoom_out();
jQuery(window).on('scroll', function(){
zoom_out();
});
});
我创建了一个 JSFiddle看看它的实际效果。
最佳答案
我已经 updated your Fiddle使用 window.requestAnimationFrame
平滑缩放.缩放动画正在振动,因为您在每个 scroll
事件上触发翻译。可以这样想:
- 用户滚动
zoom_out()
被触发并告诉元素转换它的transform
属性。您的元素现在以特定速度过渡:“长度”/过渡时间。- 更多的
scroll
事件已经过去并且都在触发zoom_out()
。下一个过渡可能会以不同的速度发生,从而产生“振动”动画。
首先,您可以摆脱 jQuery 的 transition()
方法。如果您以 60fps 或接近 60fps 的速度启动该功能,它在人眼看来会呈现平滑的动画效果,无需过渡或设置动画。
if(multiplier <= 1) {
//jQuery('#page-header-inner').stop(true, true).transition({ scale: 1/(1+multiplier), translate: '0, -50%' });
//jQuery('#page-header-custom').stop(true, true).transition({ scale: 1+multiplier });
//becomes:
jQuery('#page-header-inner').css({ scale: 1/(1+multiplier), translate: '0, -50%' });
jQuery('#page-header-custom').css({ scale: 1+multiplier });
}
}
可以通过多种方式实现以~60fps 的速度触发函数:
Throttle你的滚动事件到 60fps。
或者使用window.requestAnimationFrame就像更新的Fiddle
function zoom_out(){
//calculation code & setting CSS
window.requestAnimationFrame(zoom_out);
}
//trigger it once instead of the scroll event handler
window.requestAnimationFrame(zoom_out);
关于javascript - 使用变换 : scale 滚动振动屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34369587/