0

I want to apply a parallax effect to a background image which can be positioned everywhere in a page inside a DIV.

I try to find the "perfect" equation in order to see the background image entirely (from top to bottom) when document is scrolled, while having always image filling fully the DIV.

Finally I just want a parallax image in the middle of a page that always work whatever the image height and window height.

Here my script (it works but my calculations don't take care completely of the window height and image height ...)

$("#inner-container").on("scroll", function() {
    var scrollTop = $(this).scrollTop();
    var windowHeight = $(window).height();
    $('.parallax-container').each(function() {
        var parallaxDivPosition = $(this).position().top;
        var parallaxHeight = $(this).height();
        var scrollPosition = scrollTop + windowHeight;
        if (parallaxDivPosition <= windowHeight && parallaxDivPosition+parallaxHeight >= 0) {
            var parallaxFactor = parallaxHeight/windowHeight;
            var parallaxShift = parallaxHeight*parallaxFactor;
            var parallaxImgPos = parallaxDivPosition-windowHeight;
            var imagePosition = Math.round(parallaxImgPos-parallaxShift)*0.2;
            $(this).children().css('-webkit-transform', 'translate3d(0px, '+imagePosition+'px, 0px)');
        }
    })
})

here a fiddle: http://fiddle.jshell.net/uccE4/12/

4

1 回答 1

0

我懂了。最后它很简单(在纸上写了两个方程之后!!哈哈)

$('*').scroll(function() {
    var windowHeight = $(window).height();
    $('.parallax-container').each(function() {
        var parallaxDivPosition = $(this).position().top;
        var parallaxHeight = $(this).height();
        var parallaxTop = parallaxDivPosition - windowHeight;
        var parallaxBottom = parallaxHeight + parallaxDivPosition;
        if (parallaxTop < 0 && parallaxBottom > 0) {
            var parallaxFactor = 50/(windowHeight+parallaxHeight);
            var parallaxposition = Math.abs(parallaxTop)*parallaxFactor;
            $(this).children().css('-webkit-transform', 'translate3d(0px, '+-parallaxposition+'%, 0px)');
        }
    })
})

因此,当底部 div 图像背景是窗口的顶部时,我将看到图像的底部。当顶部 div 图像背景位于窗口底部时,我将看到图像的顶部......

所以无论图像的高度还是窗口的高度,当我滚动时,我总是会显示整个图像......

于 2013-10-16T23:42:12.840 回答