首页 > 解决方案 > 计算水平视差的div左边缘和视口左边缘之间的距离

问题描述

当我查询容器的左侧位置时,即使在我滚动时它也会返回静态数字。这是因为没有启用 x-scroll 吗?如果是这样,我应该如何重组我的代码?

jsfiddle:https ://jsfiddle.net/0xcbmrjo/

和js:

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
  })

})

标签: javascriptcssscroll

解决方案


根据 MDN,offsetLeftoffsetParent属性中读取,这是“对最接近(包含层次结构中最近)定位的祖先元素的元素的引用”(https://developer.mozilla.org/en-US/docs/Web /API/HTMLElement/offsetParent)。在我们的例子中,我们重新定位.wrapper元素,它带有所有子元素(.container元素),以便.container元素相对于它们的直接祖先保持恒定的偏移量,因此是“静态”偏移量。


推荐阅读