You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用IntersectionObserver检测100vh元素完全可见并拦截滚动?

解决100vh元素完全可见时阻止页面滚动的问题

你的问题出在两个核心点:

  1. threshold: 1 的触发条件过于苛刻:IntersectionObserver 的 threshold:1 要求元素自身100%区域都在视口内才会触发回调。对于高度为100vh的元素来说,只有当元素顶部刚好对齐视口顶部、底部刚好对齐视口底部时才满足,这在实际滚动场景中几乎很难触发。
  2. 代码只添加了滚动阻止监听,未在元素不可见时移除,会导致后续滚动一直被锁定。

下面是修正后的解决方案:

思路

  • 去掉严格的 threshold 限制,改为在回调中动态判断元素是否满足“完全可见/覆盖视口”的条件。
  • 根据元素的可见状态,动态添加/移除滚动阻止事件,避免不必要的滚动锁定。

修正后的代码

const stopDiv = document.querySelector('.stopDiv');
let isScrollBlocked = false;

const observer = new IntersectionObserver((entries) => {
  const entry = entries[0];
  // 针对100vh元素,判断是否完全覆盖视口(可视区域被元素填满)
  const isFillingViewport = entry.intersectionRect.height === window.innerHeight;
  
  if (isFillingViewport && !isScrollBlocked) {
    // 添加滚动阻止监听
    window.addEventListener('mousewheel', blockScroll, { passive: false });
    window.addEventListener('wheel', blockScroll, { passive: false });
    window.addEventListener('DOMMouseScroll', blockScroll, { passive: false });
    isScrollBlocked = true;
  } else if (!isFillingViewport && isScrollBlocked) {
    // 移除滚动阻止监听
    window.removeEventListener('mousewheel', blockScroll);
    window.removeEventListener('wheel', blockScroll);
    window.removeEventListener('DOMMouseScroll', blockScroll);
    isScrollBlocked = false;
  }
}, {
  // 设置多阈值,确保滚动过程中及时触发回调
  threshold: [0, 0.5, 1]
});

observer.observe(stopDiv);

function blockScroll(e) {
  e.preventDefault();
  return false;
}

关键调整说明

  • 判断条件优化:用 entry.intersectionRect.height === window.innerHeight 检测元素是否填满整个视口,只要元素的可见高度等于视口高度,就判定为需要阻止滚动,这比 threshold:1 的触发条件更宽松且贴合实际场景。
  • 动态监听管理:通过 isScrollBlocked 状态变量避免重复添加/移除事件,确保只有在元素符合条件时才锁定滚动,离开视口范围后恢复正常滚动。
  • 多阈值触发:设置 threshold: [0, 0.5, 1] 让IntersectionObserver在元素可见比例变化时更频繁地触发回调,保证状态切换的及时性。

如果你的实际需求是元素完全处于视口内(而非覆盖视口),可以把判断条件改为:

const isFullyVisible = entry.isIntersecting && entry.intersectionRatio === 1;

内容的提问来源于stack exchange,提问作者pindol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:23:13