JS 如何判断一个元素是否在可视区域内?
- 方法一:
offsetTop、scrollTop
- 方法二:
getBoundingClientRect()
- 方法三:
Intersection Observer
方法一:offsetTop、scrollTop
el.offsetTop - document.documentElement.scrollTop <= viewPortHeight;
function isInViewPortOfOne(el) {
const viewPortHeight =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
const offsetTop = el.offsetTop;
const scrollTop = document.documentElement.scrollTop;
const top = offsetTop - scrollTop;
return top <= viewPortHeight;
}
方法二:getBoundingClientRect
- 返回值是一个 DOMRect 对象,拥有 left, top, right, bottom, x, y, width, 和 height 属性
const target = document.querySelector(".target");
const clientRect = target.getBoundingClientRect();
console.log(clientRect);
function isInViewPort(element) {
const viewWidth = window.innerWidth || document.documentElement.clientWidth;
const viewHeight =
window.innerHeight || document.documentElement.clientHeight;
const { top, right, bottom, left } = element.getBoundingClientRect();
return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
}
方法三:Intersection Observer
- Intersection Observer 即重叠观察者,从这个命名就可以看出它用于判断两个元素是否重叠,因为不用进行事件的监听,性能方面相比 getBoundingClientRect 会好很多
- 使用步骤主要分为两步:创建观察者和传入被观察者
const options = {
threshold: 1.0,
root:document.querySelector('#scrollArea')
};
const callback = (entries, observer) => { ....}
const observer = new IntersectionObserver(callback, options);
const callback = function(entries, observer) {
entries.forEach(entry => {
entry.time;
entry.rootBounds;
entry.boundingClientRect;
entry.intersectionRect;
entry.intersectionRatio;
entry.target;
});
};
const target = document.querySelector('.target');
observer.observe(target);
完整代码
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<title>Document</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
}
.target {
margin: 5px;
width: 20px;
height: 20px;
background: red;
}
</style>
</head>
<body>
<div class="container"></div>
</body>
</html>
<script>
(() => {
const $container = $(".container");
function createTargets() {
const htmlString = new Array(10000).fill('<div class="target"></div>').join("")
$container.html(htmlString)
}
createTargets();
const $targets = $(".target");
function isInViewPort(el){
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
const {top,right,left,bottom} = el.getBoundingClientRect();
return top >= 0 && left >= 0 && bottom <= viewPortHeight && right <= viewPortWidth
}
$(window).on("scroll",()=>{
console.log("scroll!!");
$targets.each((index,element)=>{
if(isInViewPort(element)){
$(element).css("background-color","blue")
}
})
})
})();
</script>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"
integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.test {
width: 200px;
height: 1000px;
background: orange;
}
.box {
width: 150px;
height: 150px;
margin: 50px;
background: red;
}
#sta {
position: fixed;
left: 40%;
top: 40%;
width: 200px;
height: 100px;
background: greenyellow;
}
</style>
</head>
<body>
<div class="test">test</div>
<div class="box">box</div>
<div id="sta">初始化</div>
</body>
</html>
<script>
(() => {
var status_node=document.querySelector("#sta");
const box = document.querySelector('.box');
const intersectionObserver = new IntersectionObserver((entries) => {
entries.forEach((item) => {
if (item.isIntersecting) {
box.innerText = '进入可视区域';
status_node.innerText = '进入可视区域';
console.log('进入可视区域');
}else{
box.innerText = '出去了';
status_node.innerText = '出去了';
}
})
});
intersectionObserver.observe(box);
})();
</script>
特殊字符描述:
- 问题标注
Q:(question)
- 答案标注
R:(result)
- 注意事项标准:
A:(attention matters)
- 详情描述标注:
D:(detail info)
- 总结标注:
S:(summary)
- 分析标注:
Ana:(analysis)
- 提示标注:
T:(tips)
打开App,阅读手记