简体   繁体   中英

jQuery - Parallax Effect - Change Background Position to “Center Center”

I've implemented the below jQuery parallax effect into my website (taken from http://www.brandaiddesignco.com/insights/parallax-scrolling-made-easy/ ):

var top_header = '';
$(document).ready(function(){
  top_header = $('.header-container');
});
$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"center "+(st*.5)+"px"});
});

It works great, and all I needed to do was simply applying it to the class containing the background. However, the starting position of the background image is top center and I would like to change it to center center. I have tried changing the code to the following, which made the plugin stop working:

top_header.css({'background-position':"center center"+(st*.5)+"px"});

Any suggestions?

Thanks!

Figured it out... got it working with CSS calc() :

$(document).ready(function(){

var top_header = $('.header-container');
top_header.css({'background-position':'center center'}); // better use CSS

$(window).scroll(function () {
var st = $(this).scrollTop();
top_header.css({'background-position':'center calc(50% + '+(st*.5)+'px)'});
});
});

http://codepen.io/anon/pen/qEgQzK?editors=001

Original answer was edited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM