我正在尝试为我的背景图片制作一个简单的视差效果,一切似乎都正常,但背景图片在第一次滚动时跳转,然后就可以了!我似乎无法弄清楚为什么它继续跳跃,实时预览:http://loai.directory/gallery
HTML:
<div class="topSection parallax">
<div class="content">
</div>
</div>
CSS:
#page {
background-color: #3F8AE4;
padding-top: 80px;
text-align: left;
}
/*Wrappers*/
.wrapper {
background-color: #ffffff;
}
.wrapper.A {
background-color: #EDEDED;
border-top: 1px solid rgba(0,0,0,0.1);
border-bottom: 1px solid rgba(0,0,0,0.1);
}
/*Content Container*/
.content {
width: 1024px;
padding: 50px 20px;
margin: auto;
overflow: hidden;
position: relative;
}
/*Top Section*/
.topSection {
color: #fff;
background-color: #3F8AE4;
border-bottom: 1px solid rgba(0,0,0,0.1);
padding: 10px 0;
}
.parallax {
background: url(../images/backgruond.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding: 150px 0;
}
JS:
// Y axis scroll speed
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.topSection').each(function() {
var $element = $(this);
// subtract some from the height b/c of the padding
var height = $element.height()-0;
$(this).css('background-position', '50%' + Math.round((height - pos) * velocity) + 'px');
});
};
$(window).bind('scroll', update);
最佳答案
您的 background-position
通过默认 CSS 设置为 center center
,但是一旦您开始滚动,它就会设置为 50% 50px
...所以跳跃来自从居中到计算的垂直位置。
您可以通过两种方式解决这个问题,要么将您的初始 css 设置为:
background: url(../images/backgruond.jpg) no-repeat 50% 50px fixed;
因为您知道这是您开始滚动时设置的位置,
或者,除了滚动之外,只需在页面加载时调用您的 update()
函数,从而允许立即计算位置。
例如:
$(window).bind('scroll', update);
update();
关于javascript - 背景图像在第一次滚动时跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23225166/