簡體   English   中英

窗口計算中的視差背景位置

[英]Parallax background position in window calculation

有人可以幫我解決一下最初出現的簡單功能,但是現在我可以拔頭發了嗎?

我正在使用綁定到窗口滾動功能的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樣式溢出:滾動)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM