Parallax Scrolling Background Images in Wrong Position on Page Reload (When Not at Top of Page)

时间:2015-10-06 08:49:52

标签: scroll refresh reload parallax

I'm developing a scaling web page with three image-based layers of parallax scrolling. Only the first two layers are set up with parallax javascript. The third layer is set at normal scroll speed 0, so it doesn't require any scroll speed modification.

My problem is that when the page is reloaded (on Firefox, at least) when you aren't at the top of the page, those two layers load in the wrong place, but then correct themselves once you start scrolling.

I believe the problem has something to do with the position attribute. Changing to "relative" has the same effect, changing to "fixed" has a similar effect (except on reloading, the layers act like the top of the viewport is the top of the page), and having no position attribute causes them to not be layered and not have a parallax scrolling effect.

This is the javascript I'm using for the parallax effect:

$(window).scroll(function(e){
  parallax();
});
function parallax(){
  var scrolled = $(window).scrollTop();
  $('.bg').css('top',-(scrolled*-0.7)+'px');

  $('.stairs').css('top',-(scrolled*-0.5)+'px');

}

And here's a simplified version of my page with placeholder graphics on a jfiddle: http://jsfiddle.net/4spur9ch/

You can see what I mean by slightly scrolling down, then right clicking inside the result box, then going to This Frame > Reload Frame

This is the last kink that needs to be worked out before I can continue. Any help would be greatly appreciated.

Edit: It's possible it could have something to do with the 'top' in the javascript, but removing it causes problems.

1 个答案:

答案 0 :(得分:0)

$(window).scroll(function(e){
  parallax();
});

/*Needed to add this line:*/
$(window).trigger("scroll")

function parallax(){
  var scrolled = $(window).scrollTop();
  $('.bg').css('top',-(scrolled*-0.7)+'px');

  $('.stairs').css('top',-(scrolled*0.3)+'px');
}