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

修改文本行遮罩动画:从滚动触发改为文本可视时触发

修改文本行遮罩动画为视图触发播放

原代码的动画是随滚动 scrub 播放,现在调整为当文本行进入视图时自动播放一次遮罩动画,具体修改如下:

修改后的完整代码

JavaScript

let typeSplit;
// 拆分文本
function runSplit() {
  typeSplit = new SplitType(".split-lines", {
    types: "lines, words"
  });
  $(".line").append("<div class='line-mask'></div>");
  createAnimation();
}
runSplit();
// 窗口 resize 时更新文本拆分
let windowWidth = $(window).innerWidth();
window.addEventListener("resize", function () {
  if (windowWidth !== $(window).innerWidth()) {
    windowWidth = $(window).innerWidth();
    typeSplit.revert();
    runSplit();
  }
});

gsap.registerPlugin(ScrollTrigger);

function createAnimation() {
  $(".line").each(function (index) {
    let tl = gsap.timeline({
      scrollTrigger: {
        trigger: $(this),
        // 触发时机:元素顶部进入视口底部1/3位置时启动
        start: "top 70%",
        // 标记动画只触发一次
        once: true
      }
    });
    tl.to($(this).find(".line-mask"), {
      width: "0%",
      duration: 0.8,
      ease: "power2.out"
    });
  });
}

CSS

body {
  background: #000;
}
.split-lines {
  display: block;
  margin: 25% auto;
  color: #fff;
  font-size: 28px;
  line-height: 36px;
  width: 50%;
}
.line {
  position: relative;
  overflow: hidden; /* 新增:防止遮罩超出文本行范围 */
}
.line-mask {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #000;
  opacity: 0.65;
  height: 100%;
  width: 100%;
  z-index: 2;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/ScrollTrigger.min.js"></script>
<script src="https://unpkg.com/split-type"></script>

<div class="split-lines">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

关键修改点

  • 移除ScrollTrigger的scrub: 1配置,改为once: true,确保动画仅在元素首次进入视图时播放一次
  • 调整start参数为"top 70%",让文本行滚动到视口下方1/3位置时触发动画(可根据需求调整数值,比如"top 80%"会更早触发)
  • 给.line类添加overflow: hidden,避免遮罩元素超出文本行范围
  • 微调动画duration和ease参数,让过渡效果更自然

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:55:16