zoukankan      html  css  js  c++  java
  • 如何利用JS检查元素是否在视口内

    前言

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

    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 要好。

    https://www.98891.com/article-81-1.html

    2. Intersection Observer

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

    // 获取要监测的元素
    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);
    });
  • 相关阅读:
    如何写一个邮件模板页面
    java集合List,Set,Map等集合
    参悟python元类(又称metaclass)系列实战(二)
    参悟python元类(又称metaclass)系列实战(一)
    对Python"一切皆对象"的小参悟
    Linux设置ntp客户端
    JMeter BeanShell向文件中写入内容
    JMeter处理接口签名(sign)
    JMeter处理动态的签名内容
    多线程总结,ThreadPoolExecutor创建线程池,
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/14933960.html
Copyright © 2011-2022 走看看