jQuery - 视差效果 - 将背景位置更改为"中心"

Dom*_*ran 1 jquery background parallax

我在我的网站上实现了以下jQuery视差效果(取自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"});
});
Run Code Online (Sandbox Code Playgroud)

它工作得很好,我需要做的就是将它应用到包含背景的类中.但是,背景图像的起始位置是顶部中心,我想将其更改为居中中心.我已经尝试将代码更改为以下内容,这使插件停止工作:

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

有什么建议?

谢谢!

Shi*_*iel 6

想出来......让它使用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)'});
});
});
Run Code Online (Sandbox Code Playgroud)

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

原始答案已编辑.