gpt4 book ai didi

javascript - CSS Scroll Snap 获取事件元素

转载 作者:行者123 更新时间:2023-12-05 00:33:08 25 4
gpt4 key购买 nike

我对 CSS scroll snap 有疑问.我想通过 JavaScript 检测捕捉到的元素并分配它,例如 CSS 类或类似的。
不幸的是,我还没有找到检测捕捉元素的方法。背景:我有一个带有子项的列表,它们是滚动的,列表中的中间项总是应该突出显示:
布局
Layout
我已经用 rootMargin 测试了相交观察器来检测垂直居中的元素,但它的错误多于有用。
HTML

<div class="timeline-menu-dropdown-years-list-container">
<ul class="timeline-menu-dropdown-years-list timeline-menu-dropdown-years-text" id="yearcontainer">
<li id="2010" class="timeline-dropdown-year" data-target="year-2010">2010</li>
<li id="2009" class="timeline-dropdown-year" data-target="year-2009">2009</li>
<li id="2008" class="timeline-dropdown-year" data-target="year-2008">2008</li>
<li id="2007" class="timeline-dropdown-year" data-target="year-2007">2007</li>
<li id="2006" class="timeline-dropdown-year" data-target="year-2006">2006</li>
<li id="2005" class="timeline-dropdown-year" data-target="year-2005">2005</li>
<li id="2004" class="timeline-dropdown-year" data-target="year-2004">2004</li>
<li id="2003" class="timeline-dropdown-year" data-target="year-2003">2003</li>
<li id="2002" class="timeline-dropdown-year" data-target="year-2002">2002</li>
<li id="2001" class="timeline-dropdown-year" data-target="year-2001">2001</li>
<li id="2000" class="timeline-dropdown-year" data-target="year-2000">2000</li>
</ul>
</div>
CSS
.timeline-menu-dropdown-years-list-container {
max-height: 250px;
overflow: scroll;
scroll-snap-type: y mandatory;
-ms-overflow-style: none; /* Internet Explorer and Edge */
scrollbar-width: none; /* Firefox */
padding-top: 45%;
padding-bottom: 40%;
scroll-padding-top: 45%;
scroll-padding-bottom: 40%;
}

.timeline-dropdown-year {
color: white;
font-size: 14px;
border-bottom: 2px solid white;
margin-right: 11%;
margin-left: 34%;
scroll-snap-align: center;
}
我该如何解决?
最后,您应该能够滚动浏览此时间线。事件元素应始终对齐中心并在视觉上突出显示。

最佳答案

我也有同样的问题。我在这里用 JavaScript 解决了这个问题:Implementation of CSS scroll snap event stop and element position detection

[].slice.call(container.children).forEach(function (ele, index) {
if (Math.abs(ele.getBoundingClientRect().left - container.getBoundingClientRect().left) < 10) {
// The 'ele' element at this moment is the element currently
// positioned. Add class .active for example!

} else {
// The 'ele' element at the moment is not
// the currently positioned element
}
});
把它放在事件滚动中:
// Timer, used to detect whether horizontal scrolling is over
var timer = null;
// Scrolling event start
container.addEventListener('scroll', function () {
clearTimeout(timer);
// Renew timer
timer = setTimeout(function () {
// No scrolling event triggered. It is considered that
// scrolling has stopped do what you want to do, such
// as callback processing
}, 100);
});

关于javascript - CSS Scroll Snap 获取事件元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66852102/

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