元素在窗口中的位置

518 阅读2分钟

javascript方法

  1. node.contains()返回的是一个布尔值,来表示传入的节点是否为该节点的后代节点。

  2. Element.getBoundingClientRect() 返回元素的大小及其相对于视口的位置。right 和 left 的差值与 offsetWidth 的值相等,而 bottom 和 top 的差值与 offsetHeight 相等

image-20210517183345107.png

  1. IntersectionObserver 一种异步检测目标元素与祖先元素或 viewport相交情况变化的方法。

blog.csdn.net/weixin_4383…

www.zhangxinxu.com/wordpress/2…

developer.mozilla.org/zh-CN/docs/…

function query(selector) {
  return Array.from(document.querySelectorAll(selector));
}

var observer = new IntersectionObserver(
  function(changes) {
    changes.forEach(function(change) {
      var container = change.target;
      var content = container.querySelector('template').content;
      container.appendChild(content);
      observer.unobserve(container);
    });
  }
);

query('.lazy-loaded').forEach(function (item) {
  observer.observe(item);
});
{
  time: 3893.92,
  rootBounds: ClientRect {
    bottom: 920,
    height: 1024,
    left: 0,
    right: 1024,
    top: 0,
    width: 920
  },
  boundingClientRect: ClientRect {
     // ...
  },
  intersectionRect: ClientRect {
    // ...
  },
  intersectionRatio: 0.54,
  target: element
}
// time:可见性发生变化的时间,是一个高精度时间戳,单位为毫秒
// target:被观察的目标元素,是一个 DOM 节点对象
// rootBounds:根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回null
// boundingClientRect:目标元素的矩形区域的信息
// intersectionRect:目标元素与视口(或根元素)的交叉区域的信息
// intersectionRatio:目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0

css方法

  1. clientHeight、clientWidth

clientHeight:clientWidth.png

​ 【获取浏览器窗口的高和宽:不包括工具栏/滚动条】

const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
  1. scrollHeight、scrollWidth

(1)document对象的scrollHeight和scrollWidth属性就是网页的大小,意思就是滚动条滚过的所有长度和宽度。

(2)如果网页内容能够在浏览器窗口中全部显示,不出现滚动条,那么网页的clientWidth和scrollWidth应该相等。

  1. offsetTop、offsetLeft

该元素的左上角与父容器(offsetParent对象)左上角的距离.

offsetTop:offsetLeft.png

  1. scrollTop、scrollLeft

scrollTop:scrollLeft.png

引用: juejin.cn/post/684490…

判断元素是否在可视区域

  1. el.offsetTop - document.documentElement.scrollTop = el.getBoundingClientRect().top

  2. el.offsetTop - document.documentElement.scrollTop <= viewPortHeight

  3. intersectionRatio > 0 && intersectionRatio <= 1