【发布时间】:2020-12-24 16:28:19
【问题描述】:
上下文
我正在制作一个博客网站,我希望有一个粘性元素,当用户滚动时,它会在每个新年和每个月更新。这样标题就会显示列出的博客文章的当前月份和年份。
在编码的时候,我尝试用 HTML 来实现效果,如果不行就用 CSS,如果不行就用 JS。我认为这是一种很好的做法,因为它使用了内置功能并减少了所需的计算资源,但如果您不同意这种观点,请告诉我。
问题
理想情况下,元素的样式会在“卡住”时改变。为此,我查看了使用 IntersectionObserver 的 David Walsh's solution,但在添加多个元素时会出现故障。
我面临的主要问题是,当有多个条目时,脚本会在某个元素位于窗口的底部边框时将其检测为“固定”。
代码
这是一个sn-p。我也发了jsfiddle with the same code。
//Essentially putting David Walsh's code in a loop
document.querySelectorAll(".myElement").forEach((i) => {
const observer = new IntersectionObserver(([i]) => i.target.classList.toggle("is-pinned", i.intersectionRatio < 1),
{threshold: [1]});
observer.observe(i);
})
#parent {
height: 2000px;
}
.myElement {
position: sticky;
top: -1px;
}
/* styles for when the header is in sticky mode. The transition times accentuate the undesired effect */
.myElement.is-pinned {
color: red;
transition: color 0.3s, background-color 0.3s;
background-color: orange;
}
<div id="parent">
<!-- Adding more than one 'hello' element. The br's are here to add vertical space and be longer than the viewport height -->
<br><br><br><br>
<div class="myElement">Hello!</div>
<br><br><br><br>
<div class="myElement">Hello 2!</div>
<br><br><br><br>
<div class="myElement">Hello 3!</div>
<br><br><br><br>
<div class="myElement">Hello 4!</div>
<br><br><br><br>
<div class="myElement">Hello 5!</div>
<br><br><br><br>
<div class="myElement">Hello 6!</div>
<br><br><br><br>
<div class="myElement">Hello 7!</div>
<br><br><br><br>
<div class="myElement">Hello 8!</div>
</div>
【问题讨论】:
标签: javascript css sticky intersection-observer html-heading