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

CSS+Vanilla JS遮罩动画:添加不受影响的前后Div求助

解决方案:添加不受遮罩影响的前后元素

核心思路

将遮罩效果仅限定在.container.fullscreen2容器内部,前后新增的Div作为同级独立元素,不继承遮罩样式,即可实现不受影响的效果。

1. 调整HTML结构

直接在.container.fullscreen2前后添加独立的内容区块:

<!-- 前置不受遮罩影响的内容 -->
<div class="unmasked-section before">
  <h2>前置内容</h2>
  <p>该区域完全不受圆形遮罩动画影响</p>
</div>

<div class="container fullscreen2">
  <!-- 原有遮罩动画相关内容 -->
  <div class="masked-content">
    <h1>标题文本</h1>
    <div class="k-marker">K</div>
  </div>
</div>

<!-- 后置不受遮罩影响的内容 -->
<div class="unmasked-section after">
  <h2>后置内容</h2>
  <p>滚动过遮罩区域后,此区域正常显示</p>
</div>

2. 修正CSS遮罩作用范围

确保遮罩属性仅作用于.container.fullscreen2,而非父级或全局:

/* 不受遮罩影响的通用样式 */
.unmasked-section {
  padding: 3rem 2rem;
  background: #f5f5f5;
  color: #222;
}

/* 仅给目标容器应用遮罩 */
.container.fullscreen2 {
  position: relative;
  height: 100vh;
  overflow: hidden;
  /* 遮罩核心属性(根据原有实现调整,此处以mask为例) */
  -webkit-mask-image: radial-gradient(circle, transparent 0%, black 0%);
  mask-image: radial-gradient(circle, transparent 0%, black 0%);
  mask-size: 0% 0%;
  mask-position: center;
  mask-repeat: no-repeat;
  transition: mask-size 0.25s ease-out;
}

/* 滚动触发的遮罩展开效果 */
.container.fullscreen2.mask-active {
  mask-size: 220% 220%;
}

3. 保持原有JS逻辑不变

滚动监听逻辑仅针对.container.fullscreen2进行遮罩尺寸控制,无需修改:

window.addEventListener('scroll', () => {
  const targetContainer = document.querySelector('.container.fullscreen2');
  const containerRect = targetContainer.getBoundingClientRect();
  const scrollPos = window.scrollY || document.documentElement.scrollTop;
  
  // 计算滚动进度,控制遮罩展开比例
  const progress = Math.max(0, Math.min(1, (scrollPos - containerRect.top + window.innerHeight) / (containerRect.height + window.innerHeight)));
  targetContainer.style.maskSize = `${progress * 220}% ${progress * 220}%`;
});

关键注意事项

  • 如果原有实现中遮罩是通过父容器或全局伪元素实现的,需将遮罩代码迁移至.container.fullscreen2本身
  • 前后新增的Div必须是.container.fullscreen2的同级元素,不能嵌套在其内部
  • 若使用clip-path替代mask,逻辑完全一致,只需将mask-*属性替换为clip-path相关值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:24:59