视差背景位置在窗口计算



有没有人能帮我解决这个最初看起来很简单的功能,但现在却让我头疼的问题?

我使用了一个非常简单的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 });
            });
        });
    }); 

对于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样式有溢出:scroll)

相关内容

  • 没有找到相关文章

最新更新