当目标元素到达浏览器的中点时,我试图创建视差效果。将元素滚动到中点之后,我想更新transform: translate
CSS,添加一个细微的动作。
我是JavaScript的新手,但是设法写了一条if
语句,该语句寻找越过中点的元素。但是,我真的很难满足添加运动/偏移量所需的方程式,尤其是在正确的时间从0开始平移。
下面是我当前的代码,我真的很感谢任何建议:
// get the elements
const container = document.querySelector('.container')
const tag = document.querySelector('.box')
// get elements positioning/height
const tagRect = tag.getBoundingClientRect()
const tagTop = tagRect.top
const tagHeight = tagRect.height
// create the offset
const tagPosition = -(tagHeight - tagTop)
const moveBox = () => {
// get the scroll position
const pixels = window.pageYOffset
// get the window heights
const windowHeight = window.innerHeight
const halfWindowHeight = windowHeight / 2
const tagBounding = tag.getBoundingClientRect()
const tagLocation = tagBounding.top
// testing a created value
const offset = -(pixels - tagPosition) / 2
const value = Math.min(offset, 0) * .5
if (tagLocation <= halfWindowHeight) {
tag.style.transform = `translate3d(0,${value}px,0)`
tag.style.backgroundColor = `goldenrod`
} else {
tag.style.transform = `translate3d(0,0,0)`
tag.style.backgroundColor = `oldlace`
}
}
document.addEventListener("scroll", moveBox)
这里是完整笔https://codepen.io/anon/pen/QobPmx的链接。再次感谢。