如何利用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 要好。
2. Intersection ObserverThe 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 viewport.
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);});参考
how-to-check-an-element-is-in-viewport-4bcl
Intersection Observer API
总结到此这篇关于如何利用JS检查元素是否在视口内的文章就介绍到这了,更多相关JS检查元素在视口内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
1. Python Tricks 使用 pywinrm 远程控制 Windows 主机的方法2. Vue中keep-alive 实现后退不刷新并保持滚动位置3. CSS 使用Sprites技术实现圆角效果4. 用于ETL的Python数据转换工具详解5. django filters实现数据过滤的示例代码6. springboot集成与使用Sentinel的方法7. 不使用XMLHttpRequest对象实现Ajax效果的方法小结8. IntelliJ IDEA基于SpringBoot如何搭建SSM开发环境的步骤详解9. 存储于xml中需要的HTML转义代码10. JSP中param动作的实例详解

网公网安备