gpt4 book ai didi

navbar - 路口观察器 - 突出显示当前部分

转载 作者:行者123 更新时间:2023-12-05 02:14:16 24 4
gpt4 key购买 nike

每当某个部分部分在 View 中或部分在 View 之外时,我正在尝试激活和停用导航栏项目的类。如果我完全向下或向上滚动页面,代码可以正常工作。问题是如果我在一个部分的中间改变方向。

似乎该部分需要先 100% 离开 View ,然后再回到 View 中,以便类激活或停用(我相信发生这种情况是因为我们正在检查 entry.isIntersecting 为 true,首先需要将其更改为 false)。尽管如此,这会导致不良行为。

我试过摆弄 if 语句来检查 entry.intersectionRatio,但我似乎也无法让它工作。我也在不同的浏览器中尝试过,以防万一,但行为仍然相同。

我该如何解决这个问题?

这是一些 code这显示了这种“错误”行为。它看起来像这样:

const sections = document.querySelectorAll('div.screen');
const config = {
rootMargin: '-50px 0px -55%'
};

let observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
intersectionHandler(entry);
}
});
}, config);

sections.forEach(section => {
observer.observe(section);
});

function intersectionHandler(entry) {
const id = entry.target.id;
const currentlyActive = document.querySelector('nav li.active');
const shouldBeActive = document.querySelector('nav li[data-ref=' + id + ']');

if (currentlyActive) {
currentlyActive.classList.remove('active');
}
if (shouldBeActive) {
shouldBeActive.classList.add('active');
}
}

代码笔来自this文章。

提前致谢。

最佳答案

我一直在玩你的 CodePen 并找到了解决问题的方法。

主要思想是确保只有一个元素可以同时位于root中。为此,您需要做两件事:

首先,rootMargin 高度应该尽可能薄。

rootMargin: '-45% 0px -55%'

第二件事是为您的 .screen CSS 类添加边距。

  margin-top: 3px;

(1 或 2 像素可能太小)

该代码在 Firefox 和 Chrome 上运行良好,但在似乎未实现 InstersectionObserver API 的 Safari 上不起作用。我没有 Windows,所以无法测试 Edge 和 IE。

关于navbar - 路口观察器 - 突出显示当前部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53746874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com