HTML5或者JavaScript有没有内置的判断元素可见的API

如果元素在浏览器视窗内就可见,否则就不可见。

目前还需要根据窗口高度、元素高度、滚动距离等去计算判断,都2021年了,这种常用的API应该内置了吧。

阅读 1.7k
1 个回答
document.body.innerHTML = `
<div style="height:300px"></div>
<div id="box" style="width:200px;height:200px; background:red"></div>
<div style="height:1000px"></div>
`;

const observer = new IntersectionObserver((entries) => {
  console.log(entries[0].isIntersecting);
}, {
  root: null,
  rootMargin: "0px",
  threshold: 0
});
observer.observe(document.querySelector("#box"));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题