【发布时间】:2017-03-29 02:14:47
【问题描述】:
我正在创建视差效果,并且我已经做到了(几乎)每个元素都有不同的滚动速度。
我也这样做了,这样页面下方的元素在到达视口之前不会触发它们的滚动速度。
这是用于显示触发命令的 JS:
function isElementInViewport (el) {
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.bottom >= 0 &&
rect.left >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
我的滚动速度代码是:
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
if (isElementInViewport($('#computer'))) {
$('#computer').css({
transform' : 'translate(0px, '+ wScroll /12 +'%)'
});
}
OR 已经在页面顶部的元素:
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
$('#shape-2').css({
'transform' : 'translate(0px, -'+ wScroll /8 +'%)'
});
这里的问题是,当我将函数 isElementInViewport 添加到滚动速度时。
它使元素在显示时跳出视图,然后它会按我想要的方式滚动。
那么,它与页面的布局格格不入。
我尝试通过更改元素的位置来补偿它,以便当它显示时它会跳转到其原始位置然后开始滚动,但这并没有帮助,因为位置因不同的屏幕尺寸和分辨率而异。
我有什么办法让它在暴露时不会跳跃?
【问题讨论】:
-
你试过类似
if($(document).scrollTop() > $('#computer').offset().top - $('#computer').height() {的东西吗? -
我尝试用这段代码代替“if (isElementInViewport)”行。结果是无效的。
-
我忘记了括号。
if($(document).scrollTop() > $('#computer').offset().top - $('#computer').height()) { -
这次代码成功了,但还是同样的跳转问题。
标签: javascript jquery html css parallax