jQuery - Parallax Effect - 更改背景位置为 "居中"

问题描述 投票:1回答:1

我在我的网站上实现了下面的jQuery视差效果(取材于 http:/www.brandaiddesignco.cominsightsparallax-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"});
});

我所需要做的就是把它应用到包含背景的类中。 然而,背景图片的起始位置是顶部居中,我想把它改为居中。 我试着把代码改成下面的样子,这使得插件停止工作。

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

有什么建议吗?

谢谢!我已经实现了下面的jQuery插件。

jquery background parallax
1个回答
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)'});
});
});

http:/codepen.ioanonpenqEgQzK?editors=001。

原答案经过编辑。

© www.soinside.com 2019 - 2024. All rights reserved.