如何利用JS检查元素是否在视口内

编程学习 2021-07-04 14:07www.dzhlxh.cn编程入门
这篇文章主要给大家介绍了关于如何利用JS检查元素是否在视口内的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化随着长沙网络推广来一起学习学习吧

前言

分享两个监测元素是否在视口内的方法

1. 位置计算

使用 Element.getBoundingClientRect() 方法返回元素相对于视口的位置

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
};

获取浏览器窗口的宽高

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
  const vWidth = window.innerWidth || document.documentElement.clientWidth;
  const vHeight = window.innerHeight || document.documentElement.clientHeight;
};

判断元素是否在视口内,如图所示

const isElementVisible = (el) => {
  const rect = el.getBoundingClientRect()
  const vWidth = window.innerWidth || document.documentElement.clientWidth
  const vHeight = window.innerHeight || document.documentElement.clientHeight

  
  if (
    rect.right < 0 ||
    rect.bottom < 0 ||
    rect.left > vWidth ||
    rect.top > vHeight
  ) {
    return false
  }

  return true
}

getBoundingClientRect 方法会使浏览器发生回流和重绘,性能消耗稍大,但兼容性比 Intersection Observer 要好。

2. Intersection Observer

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's

Intersection Observer API提供了一种异步检测目标元素与祖先元素或 相交情况变化的方法。在目标元素与视口或者其他指定元素发生交集时和触发配置的回调函数。

// 获取要监测的元素
const boxes = document.querySelectorAll('.box')

// 创建观察者,配置回调函数
// 通过 isIntersecting 属性判断元素与视口是否相交
const observer = new IntersectionObserver((entries, observer) => {
 entries.forEach((entry) => {
    console.log(
      entry.target,
      entry.isIntersecting ? "visible" : "invisible"
    );
  });
})

boxes.forEach((box) => {
  observer.observe(box);
});

参考

总结

到此这篇关于如何利用JS检查元素是否在视口内的文章就介绍到这了,更多相关JS检查元素在视口内容请搜索狼蚁SEO以前的文章或继续浏览狼蚁网站SEO优化的相关文章希望大家以后多多支持狼蚁SEO!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板