有没有人能帮帮我,一个最初看起来很简单的功能,现在却让我摸不着头脑?
我使用的是绑定到窗口滚动功能的非常简单的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 });
});
});
}); 发布于 2013-06-11 07:16:11
使用包含图像的div的imgWindow,这样的内容应该是可以的:
// get the maximum window scroll
var deseapearPos = $(window).height() - $('#imgWindow').offset().top;
var imgWindowHeight=('#imgWindow').height();
var imageHeight = 500;
$(window).scroll(function() {
var currWinPos = $(window).scrollTop();
if (currWinPos < deseapearPos ) {
// if imageWindow still on sight
var newPos = /* your computation here */
// ( smthg like newPos = ( imageHeight - imgWindowHeight ) * (currWinPos/ deseapearPos ) );
$('#imgWindow').scrollTop(newPos);
}
});( imgWindow css样式有一个溢出:滚动)
https://stackoverflow.com/questions/17033560
复制相似问题