javascript - 计算水平视差的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
})
})
解决方案
根据 MDN,offsetLeft
从offsetParent
属性中读取,这是“对最接近(包含层次结构中最近)定位的祖先元素的元素的引用”(https://developer.mozilla.org/en-US/docs/Web /API/HTMLElement/offsetParent)。在我们的例子中,我们重新定位.wrapper
元素,它带有所有子元素(.container
元素),以便.container
元素相对于它们的直接祖先保持恒定的偏移量,因此是“静态”偏移量。
推荐阅读
- javascript - replace showModalDialog with jQuery UI , what is the best way?
- c# - C# SQL Server 数据库连接字符串语法错误
- java - 如何读取 .DBX 格式
- r - 嵌套 if else 语句
- php - 如何修复此脚本中意外的 $EOF?,我试图修复但不能
- angular - 角度 5:ngx-bootstrap 时间选择器语言环境
- java - 监听器永远不会被 spring cloud bus 和 kafka 调用
- php - bitmex api php,取消 1 个订单不起作用
- java - 抽象类返回
- javascript - 使用 mailto (JavaScript) 发送电子邮件 - 更改邮件正文中特定字符的字体大小或使其变为粗体