闪烁 - 在窗口滚动上更改CSS背景位置

时间:2013-02-15 22:00:40

标签: javascript css parallax

由于缺乏观点,我打算重新解释我的问题。有谁知道为什么修改Chrome和IE的窗口滚动背景位置有时会导致闪烁?

基本上这样的事情总会导致Chrome和IE中的闪烁:

$(window).scroll(function(){$(divwithbg).css('background-position','center '+positiveinteger+px')});

在任何主流浏览器中,似乎都没有闪现:

$(window).scroll(function(){$(divwithbg).css('background-position','center '+negativeinteger+px')});

如果您想查看此问题,请尝试下面的示例代码以及附加图片。如果你设置data-parallaxdirection =“0”,那将是无抖动的。如果设置data-parallaxdirection =“1”,则会产生抖动。我把我正在使用的图像附加到这篇文章中。

<!DOCTYPE html>
<html>
<head>
        <style type="text/css">
        .parallax-container {width:100%; position:relative; display:block; overflow:hidden; background-color:black; background-position:center center; background-repeat:no-repeat;}

        </style>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


        <script type="text/javascript">
var CONTAINER = window;
var AVAILHEIGHT;
$(document).ready(function(){
    $(window).scroll(ParallaxScrollEvent);
    AVAILHEIGHT = $(window).height();
    $('.parallax-container').height(AVAILHEIGHT/1.1);
});

function ParallaxScroll(obj)
{
    var containerTop = $(obj).position().top;
    var containerHeight = $(obj).height();
    var parallaxspace = parseInt($(obj).attr('data-parallaxspace'));
    var goforward = parseInt($(obj).attr('data-parallaxdirection'));
    var scrollTop =  $(window).scrollTop() + AVAILHEIGHT;

//  var links = $('.location-links'); //on contact page


    if( scrollTop > containerTop)
    {
            var pos = 0;
            if(goforward)
            {
                            // why does this cause flickering?
                var scrolled = $(window).scrollTop() - containerTop;
                pos = 1.2*scrolled;

            }
            else
            {
                            // why is this flicker free?
                pos = -1*(scrollTop-containerTop)*parallaxspace/(2*containerHeight);
            }
            $(obj).css('background-position', 'center '+pos+'px');
    }
}

function ParallaxScrollEvent()
{
    var parallaxcontainer = $('.parallax-container');
    for(var c=0; c< parallaxcontainer.length; c++)
        ParallaxScroll(parallaxcontainer[c]);
}

        </script>

</head>
<body>
<div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
            </div>
            <div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
            </div>
            <div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
            </div>

</body>
</html>

enter image description here

1 个答案:

答案 0 :(得分:3)

我解决了这个问题。

我在background-attachment:fixed添加了.parallax-container