视差的背景位置:无跳

问题描述:

中心中心我想不出解决的自己守着几十后的办法视差的背景位置:无跳

#banner .slide { 
    position: static; 
    top: 0px; 
    left: 0px; 
    z-index: 99; 
    opacity: 1; 
    display: block; 
    visibility: hidden; 
    background-image: url(http://wp-content/uploads/2260-000-01.jpg); 
} 


#banner .slide { 
    background-attachment: inherit; 
    background-repeat: no-repeat; 
    background-position: center center; 
    background-size: cover; 
    position: relative; 
} 

背景图像定位center center,你可以看到,这是故意说background-attachement不是fixed(因为它总是与盖导致图像的狭窄视图结合)。

为了达到所需的视差,我使用这个片段。

$(window).on('scroll', function(e) { 
     $('#banner .slide').css('background-position', 'center ' + $(window).scrollTop()*0.4 + 'px') 
    }) 

我有问题当然是初始滚动(在scrollTop的第一个变化),导致图像的跳跃,因为当然JS不知道是什么意思center我。

所以我的目标是保持图像的位置center center,因为我想要始终看到图像的垂直和水平中心。

你知道任何技巧或想法,我怎么能告诉JS图像的当前垂直中心,所以视差计算会从这点开始,而不是从0

感谢开始, 马特

我建议通过改变幻灯片的转换值来采取稍微不同的方法。

const parallaxables = document.querySelectorAll('.parallax'); 
 

 
function runParallaxLoop() { 
 
    requestAnimationFrame(runParallaxLoop); 
 
    parallax(); 
 
} 
 

 
function parallax() { 
 
    parallaxables.forEach(parallaxable => { 
 
     let distance = window.scrollY * 0.5; 
 
     parallaxable.style.transform = `translate3d(0,-${distance}px, 0)`; 
 
    }); 
 
} 
 

 
runParallaxLoop();
.parallax { 
 
    width: 100vw; 
 
    height: 500px; 
 
    margin-bottom: 400px; 
 
    background: url(http://lorempixel.com/1200/800/sports/) no-repeat center center; 
 
    background-attachment: fixed; 
 
}
<div class="parallax"></div>

每一帧,就转换需要由速度的一定比例与该浏览器被滚动被parallaxed的元素。

为了达到此目的,您需要修复可用于视差的元素的背景附件。

+0

有没有办法使这项工作没有固定的背景附件? – matt

+0

如果您可以使用固定在幻灯片上的位置,那会更好。与translate3d浏览器一起将能够非常便宜地执行动画,而不必涉及主线程。 – Prashant