Skip to content

如何判断元素出现在视口内

  • offsetTop - scrollTop <= 视口高度
function isInViewPortOfOne (element) {
  // 获取可视窗口的高度。兼容所有浏览器
  const screenHeight = window.innerHeight || document.documentElement.clientHeight
  	 || document.body.clientHeight;
  // 获取滚动条滚动的高度
  const scrollTop = document.documentElement.scrollTop;
  // 获取元素偏移的高度。就是距离可视窗口的偏移量。
  const offsetTop = element.offsetTop;
  // 加100是为了提前加载
  return offsetTop - scrollTop <= screenHeight + 100;
}
  • getBoundingClientRect() getBoundingClientRect() 返回值是一个 DOMRect 对象 ,拥有left, top, right, bottom, x, y, width, height属性。公式: el.getBoundingClientRect().top <= viewPortHeight
function isInViewPortOfTwo (el) {
    const screenHeight = window.innerHeight || document.documentElement.clientHeight
    	 || document.body.clientHeight;
    const top = el.getBoundingClientRect() && el.getBoundingClientRect().top;
    return top  <= screenHeight + 100;
}

img

  • IntersectionObserver
// io 为 IntersectionObserver对象 - 由IntersectionObserver()构造器创建
 var io = new IntersectionObserver((entries) => {
   // entries 为 IntersectionObserverEntry对像数组
   entries.forEach((item) => {
     // item 为 IntersectionObserverEntry对像
     // isIntersecting是一个Boolean值,判断目标元素当前是否可见
     if (item.isIntersecting) {
       // div 可见时 进行相关操作
       console.log(item.target.innerText);
       io.unobserve(item.target); //停止监听该div DOM节点
     }
   });
 }); // 不传options参数,默认根元素为浏览器视口
const divArr = [...document.querySelectorAll(".item")];
 divArr.forEach((div) => io.observe(div)); // 遍历监听所有div DOM节点

详情参考

如何判断是手机端还是移动端?

判断浏览器宽度,或者是 window.navigator

// 宽度判断
import { useWindowSize } from "react-use";
const size = useWindowSize();
setMobile(size.width <= 750 || mobile);

// window.navigator
 const userAgent =
    typeof window.navigator === "undefined" ? "" : navigator.userAgent;
const isMobile =
    /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(
    userAgent,
    );