我正在使用以下函数来检查元素在视口中是否可见:
function elementInViewport(el) {
let top = el.offsetTop;
let left = el.offsetLeft;
const width = el.offsetWidth;
const height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight)
&& left < (window.pageXOffset + window.innerWidth)
&& (top + height) > window.pageYOffset
&& (left + width) > window.pageXOffset
);
}
Run Code Online (Sandbox Code Playgroud)
但是,我想检查一个元素是否50%在视口中可见。因此,如果仅显示一半,则支票应返回true。我知道使用 Intersection Observer API 可以做到这一点,但这对我来说不是一个选项,因为我希望它与IE11.
该测试适用于一个方向(水平或垂直)。
function checkFifty(el) {
var rect = el.getBoundingClientRect();
return (
rect.top + (rect.height/2) > 0 && // top
rect.left + (rect.width/2) > 0 && // left
rect.top + (rect.height/2) < (window.innerHeight || document.documentElement.clientHeight) && // bottom
rect.left + (rect.width/2) < (window.innerWidth || document.documentElement.clientWidth) // right
);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您复制到问题中的代码不是一个好的解决方案,因为它非常慢(并且不准确)。您应该使用getBoundingClientRect并且无需任何“手动”DOM 遍历即可完成。
您可以尝试一下以查看它的实际效果:
function checkFifty(el) {
var rect = el.getBoundingClientRect();
return (
rect.top + (rect.height/2) > 0 && // top
rect.left + (rect.width/2) > 0 && // left
rect.top + (rect.height/2) < (window.innerHeight || document.documentElement.clientHeight) && // bottom
rect.left + (rect.width/2) < (window.innerWidth || document.documentElement.clientWidth) // right
);
}
Run Code Online (Sandbox Code Playgroud)
function checkFifty() {
var el = document.getElementById("element");
var rect = el.getBoundingClientRect();
console.log (
// top
rect.top + (rect.height/2) > 0 &&
// left
rect.left + (rect.width/2) > 0 &&
// bottom
rect.top + (rect.height/2) < (window.innerHeight || document.documentElement.clientHeight) &&
// right
rect.left + (rect.width/2) < (window.innerWidth || document.documentElement.clientWidth)
);
}
function showCoordinates() {
var el = document.getElementById("element");
var rect = el.getBoundingClientRect();
console.log(rect);
}Run Code Online (Sandbox Code Playgroud)
#buttons {
position: fixed;
top: 0px;
left: 0px;
}
#container {
width: 2000px;
height: 2000px;
}
#element {
margin: 800px;
width: 200px;
height: 200px;
background-color: red;
}Run Code Online (Sandbox Code Playgroud)