簡體   English   中英

如何確定滾動時是否傳遞了元素?

[英]How to find out if an element is passed while scrolling?

我試圖找出何時滾動時通過了某些元素。

  const elementTarget = document.getElementById('sidebar');

  window.addEventListener('scroll', () => {
    if (window.scrollY > elementTarget.offscrollTop) {
      console.log('passed an element');
    }
  })

示例代碼: https//codepen.io/RomanKomprs/pen/LMrPNJ

編輯:上面的代碼不起作用。 當我向下滾動並且scrollY大於側邊欄元素的偏移量時,該條件不會觸發。 我究竟做錯了什么?

getBoundingClientRect().top替換offscrollTop

const elementTarget = document.getElementById("sidebar");

window.addEventListener("scroll", () => {
  if (window.scrollY > elementTarget.getBoundingClientRect().top) {
    console.log("passed an element");
  }
});

試試吧

首先,您必須具有相同ID的元素; 其次,您需要使用.offsetTop來獲取offset的值;

if (window.scrollY > elementTarget1.offsetTop) {
  console.log('passed an element');
}

codepen.io/anon/pen/LMrYMZ

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM