窗口计算中的视差背景位置

时间:2013-06-10 22:01:06

标签: javascript jquery parallax

有人可以帮助我首先出现一个简单的功能,但现在让我把头发拉出来?

我正在使用绑定到窗口滚动功能的非常简单的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 });
            });
        });
    }); 

1 个答案:

答案 0 :(得分:1)

使用imgWindow包含图像的div,应该是这样的 好的:

// 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样式有溢出:滚动)