问题描述
我正在使用Javascript代码检查元素是否在视口中。 但是现在我有一个代码,如果元素在视口中为100%,则仅返回true。 是否有一种方法,例如,如果有10个像素,则返回true,或者如果某个百分比的元素在视口中,则返回true?
到目前为止我的代码
<script type="text/javascript">
var elem = document.getElementById("result");
var bounding = elem.getBoundingClientRect();
if (bounding.top >= 0 && bounding.left >= 0 && bounding.right <= window.innerWidth && bounding.bottom <= window.innerHeight) {
alert('in viewport');
}
</script>
解决方法
基于@Jorg的代码,这里与Intersection Observer API相同,这是一种检查交叉点的新方法。根据{{3}}
,该功能将在所有现代浏览器中正常运行,约占93.5%。设置它是为了将视口内50%的任何内容视为阈值之内。我将它的价值提高了很多,因此很容易看到它的工作原理。
您将注意到,回调仅在阈值处(在初始检查之后)被调用。因此,如果您想要一个准确的交叉点百分比,则可能需要增加检查的阈值数量。
let callback = (entries,observer) => {
entries.forEach(entry => {
entry.target.style.backgroundColor = entry.isIntersecting ? 'green' : 'red';
entry.target.innerHTML = entry.intersectionRatio;
})
}
let observer = new IntersectionObserver(callback,{
threshold: [0.5] // If 50% of the element is in the screen,we count it!
// Can change the thresholds based on your needs. The default is 0 - it'll run only when the element first comes into view
});
['div1','div2','div3','div4'].forEach(d => {
const div = document.getElementById(d);
if (div) observer.observe(div);
})
html,body {
padding: 0;
margin: 0;
}
body {
height: 200vh;
width: 200vw;
}
#div1 {
position: absolute;
left: calc(100vw - 60px - 10px);
top: 10px;
height: 100px;
width: 60px;
background-color: red;
color: white;
}
#div2 {
position: absolute;
left: 20px;
top: 10px;
height: 50px;
width: 60px;
background-color: blue;
color: white;
}
#div3 {
position: absolute;
left: calc(100vw - 260px + 50px);
top: max(calc(100vh - 350px + 120px),120px);
height: 350px;
width: 260px;
background-color: green;
color: white;
text-align: left;
}
#div4 {
position: absolute;
height: 9000px;
width: 9000px;
color: black;
background-color: yellow;
}
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<!-- enable this div to see an example of a div LARGER than your viewport. -->
<!-- <div id="div4"></div> -->
,
我猜您在寻找的是元素和视口之间的交集吗?意思是,找出div与视口有多少重叠。
使用下面的函数可以告诉您0到1之间的视口中可以容纳多少DIV。但是请注意,以这种方式div也可以比视口大 ,在这种情况下,重叠区域也小于1。
Here是一个可行的示例
const intersection = (r1,r2) => {
const xOverlap = Math.max(0,Math.min(r1.x + r1.w,r2.x + r2.w) - Math.max(r1.x,r2.x));
const yOverlap = Math.max(0,Math.min(r1.y + r1.h,r2.y + r2.h) - Math.max(r1.y,r2.y));
const overlapArea = xOverlap * yOverlap;
return overlapArea;
}
const percentInView = (div) => {
const rect = div.getBoundingClientRect();
const dimension = { x: rect.x,y: rect.y,w: rect.width,h: rect.height };
const viewport = { x: 0,y: 0,w: window.innerWidth,h: window.innerHeight };
const divsize = dimension.w * dimension.h;
const overlap = intersection(dimension,viewport);
return overlap / divsize;
}