基本上,除了本节之外,我的交叉口观察者在我设置他观察的所有元素上都表现良好。 请帮忙
<section class="introduction-section mb-5 watch">
// elements
let elements_to_watch = document.querySelectorAll('.watch');
// callback
let callback = (items) => {
items.forEach((item) => {
console.log(item.target.id);
if (item.isIntersecting) {
console.log("... now in");
item.target.classList.add("in-page");
} else {
console.log("... now out");
item.target.classList.remove("in-page");
}
});
}
// observer
let observer = new IntersectionObserver(callback, {
threshold: 0.57
});
// apply
elements_to_watch.forEach((element) => {
observer.observe(element);
});
.introduction-section {
background-color: var(--clr-dark);
align-items: center;
}
.introduction-title-container {
display: flex;
flex-grow: 1;
justify-content: center;
align-items: center;
height: 100vh;
}
.introduction-section .title {
height: 100vh;
font-size: calc(var(--fs-h2) * 1.2);
color: var(--clr-light);
text-align: center;
max-width: 30rem;
height: fit-content;
margin-bottom: 0;
top: 50%;
left: calc(25% -20rem);
position: fixed;
transition: all 0.9s cubic-bezier(0.215, 0.61, 0.355, 1);
opacity: 0;
transform: scale(0.8);
}
.introduction-title-container.in-page .title {
opacity: 1;
transform: scale(1);
}
<section class="introduction-section mb-5 watch" id=section>
<div class="row wrapper h-100 " id=wrapper>
<div class="col-12 px-0 introduction-title-container watch" id=introduction1>
<h2 class="title">
A SmartWatch is born that goes beyond all limits.
</h2>
</div>
<div class="col-12 px-0 introduction-title-container watch" id=introduction2>
<h2 class="title">For Athletes who challenge the impossible.</h2>
</div>
<div class="col-12 px-0 introduction-title-container watch" id=introduction3>
<h2 class="title">The call to the Adventure begins.</h2>
</div>
</div>
</section>
它应该将类“watch”更改为“in-page”,但由于某些原因,在本节中它不会这样做。
正如我所说, watch 类在 col-12 div 上发生了变化,但在该部分上没有发生变化,也没有在行上发生变化,因为我尝试过。
我已经在 JS 中控制台记录了 elements_to_watch 节点列表,并且该部分就在那里,所以我不明白为什么它不起作用......
最佳答案
好的,我现在看到了添加 CSS 的问题。我不完全理解为什么,但是对于“介绍”元素的精美 CSS,容器(<section>
更大。因此,将 57% 的内容放入视口(viewport)需要更大的视口(viewport)。
我不知道你到底想做什么,但是如果你从 <section>
中去掉“watch”类,你就能明白我在说什么。 ,然后新建一个IntersectionObserver
使用较小的阈值(例如 0.20 可能),并使用该观察者观察该部分(使用相同的回调)。
因此,将“ watch ”从 <section>
中删除后,JavaScript 将是:
// observer for each heading
let observer = new IntersectionObserver(callback, {
threshold: 0.57
});
// apply
elements_to_watch.forEach((element) => {
observer.observe(element);
});
// observer for section container
observer = new IntersectionObserver(callback, {
threshold: 0.20
});
observer.observe(document.getElementById("section"));
关于javascript - 交叉口观察者未观察特定的分区/部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74940561/