【发布时间】:2013-06-06 16:19:24
【问题描述】:
有人可以帮我解决最初看起来很简单的功能,但现在让我把头发拔掉了吗?
我正在使用一个非常简单的 jQuery 块,它绑定到窗口滚动功能。我相信我拥有完成这项工作所需的所有变量,但似乎没有。我的数学似乎有所欠缺。
对于由于声誉为零而无法附上图片,我深表歉意!我拥有的变量是浏览器窗口(x)、具有滚动背景图像的 div 的高度(y)、背景图像高度(z)以及 div 顶部到顶部的滚动位置浏览器窗口 (o)。
div 的背景位置需要相对于 div 在窗口中的位置移动,以便从浏览器窗口从上到下(反之亦然)滚动的 div 中看到整个图像。
我的计算如下:-
x+y gives me the whole range of movement the div will require to cover
from it first being visible to it finally leaving the screen.
z-y gives me the range of movement the background image will require to
cover for the whole image to scroll through the div as the div scrolls
through the browser window.
(z-y)/(x+y) gives me the number of pixels the background image has to
move for every 1 pixel the browser window will scroll.
As an example,
x = 200
y = 50
z = 150
o starts at -50 and ends at 200
x+y = 250 (full div movement)
z-y = 100 (bg image movement)
(z-y)/(x+y) = 0.4 bg movement per pixel scrolled
因此,随着div位置从-50一直滚动到200,bg图像需要从0滚动到-100。
我不知道如何将这些最后的线程绑在一起。谁能帮我关联这些数字?
在此先感谢,如果听起来很愚蠢,请见谅。
标记
这是我的最终代码,感谢 Vincent 和 Rob 的帮助。这应该适用于任何大小区域使用 data-type="background" 所需的任何视差滚动。速度将由浏览器高度和背景图像大小决定。再次感谢大家。
$(function(){
$(window).bind('scroll', function() {
$window = $(window);
$('section[data-type="background"]').each(function(){
var $bgobj = $(this);
var windowHeight = 0;
windowHeight = document.body.clientHeight;
var img = new Image;
img.src = $(this).css('background-image').replace(/url\(|\)$/ig, "");
var bgImgHeight = parseInt(img.height);
var divHeight = parseInt($(this).css('height'));
var scrollPos = $(this).position().top - $window.scrollTop();
var bgMovement = bgImgHeight - divHeight;
var scrollMovement = windowHeight + divHeight;
var intPos = scrollPos + divHeight;
var yPos = ((bgMovement) / (scrollMovement)) * intPos;
var coords = '50% '+ (-yPos) + 'px';
$bgobj.css({ backgroundPosition: coords });
});
});
});
【问题讨论】:
-
我在这里看不到问题。去做就对了 !你已经完成了你的计算:钩住事件,做数学,改变正确项目的 .style.pos,如果需要,preventDefault 或 stopPropagation,你就完成了。
-
您好文森特,感谢您的回复。我知道,你会认为我拥有一切。我可以让所有东西都移动,但它有点不同步,这取决于数学的最后一点。当div从-50(到200)开始并且bg从0(到-100)开始时,如何让bg位置移动正确的距离?我的数学遗漏了什么?顺便说一句,这些数字是虚构的,因为它们都是动态计算的。对不起,如果我没有任何意义。
-
你还没有解释你想做什么。您是否希望图像的顶部和 div 在视口底部对齐,然后当 div 滚动到顶部时,让底部在 div 离开视口顶部时对齐(反之亦然)?您还需要显示考虑到 div 与文档顶部的距离的完整计算。
-
谢谢罗伯。是的,这就是我需要做的。到目前为止,这是我的代码,但 yPos 计算已完成
-
抱歉,Rob,没有意识到我不能再次使用代码...这里只是 jquery 代码jsfiddle.net/RsWbu
标签: javascript jquery parallax