[英]Background center parallax effect jumps to top
I am using the below code to provide a simple parallax effect to a background image. 我正在使用以下代码为背景图像提供简单的视差效果。 Ideally in the css I want the image to be centered (not top). 理想情况下,在CSS中,我希望图像居中(而不是顶部)。 However, as soon as I start scrolling the script jumps it to top and begins the effect. 但是,一旦我开始滚动,脚本就会跳到顶部并开始效果。 I cant work out if it's possible to alter the jquery so it begins with a centred image? 我无法解决是否有可能更改jquery,使其以居中图片开始? can anyone help? 有人可以帮忙吗?
<div id="para" style="background-image: url('blah')" data-speed="8" data-type="background">
</div>
#para {
height:500px;
float:left;
width:100%;
background-size:100%;
background-position: center center;
background-repeat: no-repeat;
background-attachemnt: fixed;
}
//Parallax
$(document).ready(function() {
if ($(window).width() > 1025) {
// Cache the Window object
$window = $(window);
$('div[data-type="background"]').each(function() {
var $bgobj = $(this);
$(window).scroll(function() {
var yPos = -($window.scrollTop() / $bgobj.data('speed'));
var coords = '50% ' + yPos + 'px';
$bgobj.css({
backgroundPosition: coords
});
});
});
}
});
You can't give background-position a percentage and pixels. 您不能给背景位置一个百分比和像素。 It should be one or the other. 应该是其中之一。 Use percent units and then turn your $window.scrollTop() to a percentage as well. 使用百分比单位,然后将$ window.scrollTop()也转换为百分比。 So multiply it by 100 and then divide by $window.height(). 因此,将其乘以100,然后除以$ window.height()。
//Parallax
$(document).ready(function() {
if ($(window).width() > 1025) {
// Cache the Window object
$window = $(window);
$('div[data-type="background"]').each(function() {
var $bgobj = $(this);
$(window).scroll(function() {
var yPos = 50 - ($window.scrollTop() * 100 / $window.height() / $bgobj.data('speed'));
var coords = '50% ' + yPos + "%";
$bgobj.css({
backgroundPosition: coords
});
});
});
}
});
your data-speed attribute needs to be lower too. 您的数据速度属性也需要降低。 I found 0.5 worked well. 我发现0.5效果很好。
<div id="para" style="background-image: url('blah')" data-speed="0.5" data-type="background">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.