I am making a comment system, there is a certain block in which there are others (messages) how, when scrolling through these messages, to find out whether the user sees one particular one (for example, with the identifier x) or not,
HTML:
<div class="parent">
<div class="msg" id="a"></div>
<div class="msg" id="b"></div>
<div class="msg" id="c"></div>
<div class="msg" id="x"></div>
</div>
CSS:
.parent {
width: 100%;
height: 100%;
height: 89%;
overflow: scroll;
padding-top: 10px;
padding-bottom: 70px;
}
.msg {
width: 98%;
height: 500px;
padding: 10px;
position: relative;
margin: 0 auto;
border: 2px hsl(174deg 72% 41%) solid;
color: hsl(174deg 72% 41%);
border-radius: 20px
px
;
margin-top: 10px;
}
JS:
document.querySelector(".parent").onscroll = () => {
//what to write here?
}
That is: if the message has become visible in the general block, then paint it in yellow
I tried different options: getComputedStyle, and getBoundingClientRect, and offset, but none of this helped me, they constantly say that the message is visible
BUT: getBoundingClientRect doesn't work, I don't need to check if it's visible in the whole window, I need to check if it's ONLY visible in a div element
WHEN SCROLLING A PARENT ELEMENT
1条答案
按热度按时间hk8txs481#
正如其他用户在评论中所建议的,您正在寻找的是Intersection Observer API
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
下面是一个尝试将这个概念应用到您的场景中的演示。它没有很好地分解,但清楚地显示了一个文档,其中包含样式为
overflow-y: scroll;
的.msg
容器(.parent
)和在视口上占用空间之前和之后的其他元素。所有
.msg
元素都将在其父元素的可见空间中被观察到相交,这样每次它们中的每一个都将可见时,其id将被打印在控制台上。另外,还有一个添加的trigger
回调将在上述事件中被调用,它将检查执行操作的条件(例如,当前可见的元素是否具有id == 'c'
)。第一个