← 中文资源

简体中文版本

计算 IntersectionObserver 可见比例

根据目标矩形与交集矩形计算 visible ratio 与阈值可见性,结果保留两位小数。

阅读英文原文

题目

卡片画廊在元素进入视口时播放显示动画,并按阈值懒加载图片。给定目标矩形与浏览器给出的裁剪后交集矩形,计算可见比例以及是否达到阈值。比例需像观察器一样保留两位小数。

  • 输入:JSON 字符串,包含 target、intersection 矩形与 threshold。
  • 输出:包含 ratio 与 visible 的 JSON 字符串。
  • 公开样例:目标 200×200、交集高 100 时比例为 0.5;完全重合为 1;完全分离为 0;比例正好等于阈值时视为可见。

解题思路

先计算目标宽高,并对结果取 0 下限,避免倒置矩形产生负面积。交集在每个轴上的长度等于两边右/下边界较小值减去左/上边界较大值,若两个矩形分离,该差值为负,需要用 Math.max(0, ...) 钳制。可见面积除以目标面积得到比例,目标面积为 0 时返回 0。最后用两位小数取整,并以 >= threshold 判断可见,因此正好命中阈值也算可见,这与观察器的语义一致。

参考实现要点

  1. targetWidth 与 targetHeight 用 Math.max(0, ...) 计算。
  2. 交集宽度:Math.min(right) - Math.max(left),再取 0 下限。
  3. 交集高度同理,使用 top 与 bottom。
  4. round2 用 Math.round(value * 100) / 100,目标面积为 0 时比例取 0。
  5. 返回 { ratio, visible: ratio >= threshold }。

常见错误

  • 直接把矩形坐标相减作为交集尺寸,分离时得到很大的假重叠。
  • 忘记钳制负值,比例出现负数。
  • 用 > 而不是 >=,恰好达到阈值时不触发。
  • 用视口面积作分母,比例与元素实际可见面积无关。

验证方式

运行五个公开样例,逐项核对比例与布尔值。再测试零高度目标应得到 0 而不是 NaN;交集超出目标时比例不应大于 1。在浏览器中创建相同阈值的 IntersectionObserver,把 entry.intersectionRatio 与 entry.isIntersecting 和函数结果对比,部分可见与恰好命中阈值的场景都应在取整误差内一致。

代码示例

const round2 = (value) => Math.round(value * 100) / 100;

function observeVisibility({ target, intersection, threshold = 0 }) {
  const targetWidth = Math.max(0, target.right - target.left);
  const targetHeight = Math.max(0, target.bottom - target.top);
  const targetArea = targetWidth * targetHeight;

  const overlapWidth = Math.max(
    0,
    Math.min(target.right, intersection.right) - Math.max(target.left, intersection.left),
  );
  const overlapHeight = Math.max(
    0,
    Math.min(target.bottom, intersection.bottom) - Math.max(target.top, intersection.top),
  );

  const ratio = targetArea === 0 ? 0 : round2((overlapWidth * overlapHeight) / targetArea);

  return {
    ratio,
    visible: ratio >= threshold,
  };
}

const payload = JSON.parse(input);
console.log(JSON.stringify(observeVisibility(payload)));