检查元素是否滚动到水平视图 50%

时间:2021-04-20 15:52:22

标签: javascript jquery browser

我有一个可水平滚动的 div,其中包含列表 (li) 元素。如何检查特定列表元素是否至少滚动到水平视图 50%?

1 个答案:

答案 0 :(得分:1)

你可以使用你想要观看的父子节点的offsetLeft、clientWidth和scrollLeft。

elementToMonitor.parentNode.addEventListener("scroll", function(event) {
  const visible = this.scrollLeft + this.clientWidth,
    isStartVisible = visible >= elementToMonitor.offsetLeft + (elementToMonitor.clientWidth / 2),
    isEndVisible = visible <= elementToMonitor.offsetLeft + this.clientWidth + (elementToMonitor.clientWidth / 2);
  // if both are true, item is visible relative to scroll position
  // this does not mean, it is visible in the viewport
  if (isStartVisible && isEndVisible) {
    elementToMonitor.setAttribute("style", `color: white; background-color: purple; border: 5px solid green; border-radius: 1em;`);
  } else {
    elementToMonitor.removeAttribute("style");
  }
});
div {
  overflow: auto;
  white-space: nowrap;
}

span {
  display: inline-block;
  border: 1px solid black;
  margin-right: 0.5em;
}

.spacer {
  width: 100vw;
}

.spacer::before {
  content: "Placeholder";
}
<div>
  <span class="spacer"></span>
  <span id="elementToMonitor">Make me purple!</span>
  <span class="spacer"></span>
</div>