滚动垂直视差
我正在研究简化的垂直视差(类似于 http://nikebetterworld.com)。
我有一个快速演示 - 代码在技术上是有效的,但我在重绘时遇到了紧张的效果每次滚动后 - 似乎 JavaScript 发生得很晚。知道为什么吗?我在剧本中看不到任何真正突出的东西。
var getYPosition = function() {
if (typeof(window.pageYOffset) == 'number') {
return window.pageYOffset;
} else {
return document.documentElement.scrollTop;
}
};
$(document).ready(function(){
var sections = $(".section");
$(window).scroll(function() {
var x = getYPosition(),
y = Math.floor(x / 1600),
z = $(sections[y]).offset();
$(sections[y]).css("background-position", "0 " + (getYPosition() - z.top)/2 + "px");
});
});
I'm working on a simplified vertical parallax (similar to http://nikebetterworld.com).
I've got a quick demo working - the code technically works, but I'm getting a jittery effect on the repaint after each scroll - it seems like the javascript is happening late. Any idea why? I can't see anything in the script that really stands out.
var getYPosition = function() {
if (typeof(window.pageYOffset) == 'number') {
return window.pageYOffset;
} else {
return document.documentElement.scrollTop;
}
};
$(document).ready(function(){
var sections = $(".section");
$(window).scroll(function() {
var x = getYPosition(),
y = Math.floor(x / 1600),
z = $(sections[y]).offset();
$(sections[y]).css("background-position", "0 " + (getYPosition() - z.top)/2 + "px");
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来图像被移动了两次 - 首先是通过浏览器滚动,然后是通过
scroll()
处理程序。因此出现了抖动。您可以通过对图像使用
position:fixed
或background-attachment:fixed
来获得更清晰的效果 - 这样它们就不会受到浏览器滚动的影响,但会被移动scroll()
处理程序。你将不再让一种效果与另一种效果发生冲突。您必须相应地修改您的scroll()
处理程序。It looks like the images are being moved twice - first by the browser scroll, and then by your
scroll()
handler. Hence the jitter.You might get a cleaner effect by using
position:fixed
orbackground-attachment:fixed
for the images - this way they are unaffected by the browser scroll, but will be moved by thescroll()
handler. You'll no longer have one effect fighting with the other. You'll have to modify yourscroll()
handler accordingly.您应该检查您的滚动回调是否被调用得太频繁。如果是这种情况,您可以尝试使用 setInterval 来限制重新渲染的次数:
http:// ejohn.org/blog/learning-from-twitter/
You should check if your scroll callback is being called too often. If this is the case, you can try using setInterval to limit the number of rerenderings:
http://ejohn.org/blog/learning-from-twitter/