笔记系列之——页面滚动时,即时获取离可视区顶部最近的元素

2019-03-31  本文已影响0人  临安linan
  1. 给需要进行比较判断的元素标签上加上特殊属性(eg.tag)
  2. let tag = document.querySelectorAll("[tag]");
  3. 监听滚动事件
// (xxx.getBoundingClientRect().top) 可以获取元素距离可视区顶部的距离
window.onscroll = function () {
  let index = 0;
  for (let i = 0; i < tag.length; i++) {
    if (Math.abs(tag[i].getBoundingClientRect().top) < Math.abs(tag[index].getBoundingClientRect().top)){
      index = i;
    }
  }
// tag[i]就是所找的元素
}
上一篇 下一篇

猜你喜欢

热点阅读