5

我有css 滚动快照的问题。我想通过 javascript 检测捕捉的元素并将其分配给例如 CSS 类或类似的。不幸的是,我还没有找到检测捕捉元素的方法。背景:我有一个带有子项的列表,它们是滚动的,列表中的中间项总是应该突出显示:

布局
布局

我已经用 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;  /* IE 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;
}

任何想法?
最后,您应该能够滚动浏览此时间线,活动元素应始终对齐中心并在视觉上突出显示。

4

1 回答 1

1

我有同样的问题,我在这里用 JS 解决了它:https ://developpaper.com/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 exemple !

    } 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);
});

享受 !:)

于 2021-07-08T19:48:53.367 回答