【发布时间】:2019-07-18 16:50:50
【问题描述】:
我试图在 Chaptr 的网站上重现效果,大约在页面的一半处,滚动经过列表元素会更改粘性/固定的单独元素的类别。此处示例:https://chaptr.studio/,“品牌、创意、代码、增长”部分。
我已经设法使部分效果与以下代码一起使用,尽管它不是最干净的。无论如何,我可以得到左侧的元素列表“投资、教育、指导”,以匹配非粘性列表正在发生的事情。
const halfWindow = (window.innerHeight / 2) - 50
const listItems = document.querySelectorAll('.scroll-item')
const firstItem = listItems[0]
const lastItem = listItems[listItems.length - 1]
const updateSection = () => {
const pixels = window.pageYOffset
listItems.forEach(item => {
// find the position of each item
const itemTop = item.offsetTop - pixels
const itemBottom = (item.offsetTop + item.offsetHeight) - pixels
// first item top
const firstItemTop = firstItem.offsetTop - pixels
const firstItemBottom = (firstItem.offsetTop + firstItem.offsetHeight) - pixels
// target the first item in the array
if (firstItemBottom <= halfWindow) {
firstItem.classList.remove('active')
firstItem.classList.remove('current')
} else if (firstItemBottom >= halfWindow) {
firstItem.classList.add('current')
}
// working sort of - clean up
if ((itemTop <= halfWindow) && (itemBottom <= halfWindow)) {
item.classList.remove('active')
if (item === lastItem) {
item.classList.add('current')
}
} else if ((itemTop <= halfWindow) && (itemBottom >= halfWindow)) {
item.classList.add('active')
item.classList.remove('current')
} else {
item.classList.remove('active')
}
})
}
document.addEventListener("scroll", updateSection)
这是一个代码笔示例: https://codepen.io/anon/pen/gVOZzp?
我需要弄清楚的主要一点是,当右侧的每个列表项都变为“活动”时,如何将左侧列表项与活动匹配。
【问题讨论】:
标签: javascript jquery html scroll