我制作的视差动画有问题。效果如下:
视差元素周围有2个部分。 如果触发了滚动事件,则会移动此视差元素。
元素的移动速度由速度值定义。该值应介于-1和1之间。因此,如果速度为正,则元素将向下移动;如果速度为负,则向下移动。
为防止各部分与视差元素之间出现间隙,将计算移动元素的新高度,因此在视口内不再可见元素之前,它不会显示间隙。
如果速度值为正并且元素向下移动,这可以正常工作,但我的问题是:如果我将速度更改为负值,则视差元素的高度和位置的计算不再有效差距仍然存在。
我的想法是,这个元素的高度计算是错误的,因为它太小了,但我不能让它起作用:(
也许你们中的一些人确切知道问题所在。我真的很感激答案:) 这个问题持续了好几天。
小提琴:https://jsfiddle.net/xs74pmvq/
提前谢谢。
var parallaxElement = document.querySelector('#parallax-element');
var parallaxContainer = parallaxElement.parentNode;
var containerHeight = parallaxContainer.offsetHeight;
/**
* The speed of the parallax element. Currently ony working
* with positive values.
*
* Change this to -[0-1] to see the gap between the parallax
* element and the surrounding sections.
*
* @todo(Hero): Make negative values working.
*/
var parallaxSpeed = 0.5;
/**
* This calculates the new height of the given parallax element.
* The height is used to fill up the gap between the two sections.
* It allows the parallax element to move without showing a space.
* The height is calculated by the given speed
*/
function setParallaxHeight(element) {
var gapHeight = containerHeight - window.innerHeight;
var newHeight = containerHeight + gapHeight * Math.abs(parallaxSpeed);
// @todo(Hero): Maybe change the calculation for negative speed values.
element.style.height = newHeight + 'px';
}
/**
* This simply sets the translation value of the parallax element.
*/
function updateElement() {
var scrollY = window.scrollY;
var elementOffset = parallaxElement.getBoundingClientRect();
var elementTop = elementOffset.top + scrollY;
/**
* This is the translation value on the y axis. This will start
* the element moving above the lower bound of the viewport after
* the user scrolled to the edge of the element.
*/
var translateY = parallaxSpeed * (scrollY - elementTop);
// @todo(Hero): Maybe change the calculation for negative speed values.
parallaxElement.style.transform = 'translate3d(0,' + translateY + 'px,0)';
}
setParallaxHeight(parallaxElement);
window.onscroll = updateElement;

.section {
width: 100vw;
height: 100vh;
}
.section1 {
background-color: gray;
}
.section2 {
height: 1000px;
}
.section3 {
height: 3000px;
background-color: green;
}
.parallax-container {
height: 100%;
width: 100%;
overflow: hidden;
}
#parallax-element {
width: 100%;
height: 50%;
background: url('https://static.vecteezy.com/system/resources/previews/000/093/696/original/vector-yellow-abstract-background.jpg') no-repeat center;
background-size: cover;
}

<div class="section section1">Scroll down</div>
<div class="section section2">
<div class="parallax-container">
<div id="parallax-element"></div>
</div>
</div>
<div class="section section3">Section2</div>
&#13;
答案 0 :(得分:1)
修正了它。
更新了平移和视差元素高度的计算。此计算是负速度值的特殊情况。
翻译计算:
translateY = parallaxSpeed * (scrollY + window.innerHeight - elementTop);
计算差距:
gapHeight = (containerHeight + window.innerHeight) / (1 + parallaxSpeed);