Javascript 为水平视差计算div左边缘和视口左边缘之间的距离
当我查询容器的左侧位置时,即使在我滚动时,它也会返回静态数字。这是因为没有启用x-scroll吗?如果是这样,我应该如何重构代码 JSFIDLE: 而js:Javascript 为水平视差计算div左边缘和视口左边缘之间的距离,javascript,css,scroll,Javascript,Css,Scroll,当我查询容器的左侧位置时,即使在我滚动时,它也会返回静态数字。这是因为没有启用x-scroll吗?如果是这样,我应该如何重构代码 JSFIDLE: 而js: const body = document.querySelector("body") const wrapper = document.querySelector(".wrapper") const bodyHeight = function () { body.style.height = wrapper.offsetWidth -
const body = document.querySelector("body")
const wrapper = document.querySelector(".wrapper")
const bodyHeight = function () {
body.style.height = wrapper.offsetWidth - (window.innerWidth - window.innerHeight) +'px'
}
bodyHeight ()
window.addEventListener ("resize", bodyHeight)
document.addEventListener("scroll", function(){
let scroll = window.pageYOffset
wrapper.style.left = `${-1 * scroll}px`
const leftViewport = window.pageXOffset
const midViewport = leftViewport + (window.innerWidth/2)
const containers = document.querySelectorAll(".container")
containers.forEach(container => {
const leftContainer = container.offsetLeft
const midContainer = leftContainer + (container.offsetWidth/2)
const distanceToContainer = midViewport - midContainer
})
})
根据MDN,
offsetLeft
读取offsetParent
属性,该属性是“对位置最近(在包容层次结构中最近)的祖先元素的引用”()。在我们的例子中,我们重新定位.wrapper
元素,该元素包含所有子元素(.container
元素),以便.container
元素相对于其直接祖先保持恒定的偏移量,因此是“静态”偏移量,offsetLeft
读取offsetParent
属性,该属性是“对最接近(在包容层次结构中最接近)定位祖先元素的元素的引用”()。在我们的例子中,我们重新定位.wrapper
元素,该元素包含所有子元素(.container
元素),以便.container
元素保持相对于其直接祖先的恒定偏移量,因此是“静态”偏移量