判断元素是否在可视窗口可见 elementIsVisibleInViewport – JavaScript 实用代码片段

如果指定的元素在可视窗口中可见,则返回 true ,否则返回 false

使用 Element.getBoundingClientRect()window.inner(Width|Height) 值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true 来判断它是否部分可见。

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;
  return partiallyVisible
    ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false // (not fully visible)
elementIsVisibleInViewport(el, true); // true // (partially visible)

更多代码 JavaScript 实用代码片段 请查看 https://www.7psus5.com/30-seconds-of-code/

赞(0) 打赏
未经允许不得转载:WEBTian开发 » 判断元素是否在可视窗口可见 elementIsVisibleInViewport – JavaScript 实用代码片段

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Tian开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏