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

如何在轮播组件中实现JS文字动画进入视口时触发?

解决打字动画进入视口才触发的问题

嘿,别担心,作为JS新手遇到视口触发动画的问题太正常啦!我帮你拆解下原代码的问题,然后给出修复方案:

原代码的核心问题分析

  • 你直接在全局调用了typewriter2(),导致页面一加载动画就自动运行,完全没关联到视口触发逻辑
  • Waypoint配置里的horizontal: true是给横向滚动页面用的,普通纵向滚动的网页不需要这个参数,加上它会导致Waypoint无法正确检测元素进入视口
  • Waypoint的回调只是给元素加了show类,但根本没触发动画函数;另外offset: '100px'的逻辑可能不符合预期(它指元素顶部距离视口顶部还有100px时触发,百分比配置会更直观)
  • 你漏了引入Waypoint的核心JS文件,这会导致视口检测功能完全失效!

修复后的完整代码

HTML部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<!-- 必须引入Waypoint核心文件,否则视口检测不生效 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<link rel="stylesheet" type="text/css"/>
<body>
  <div class="unit-221-1slide-top">
    <p>After Yaakov received the blessings from his father, his brother Esav wanted to kill him. Yaakov forced to run away to the home of Lavan his uncle in Haran. Yaakov lived with Lavan for 22 years and married his two daughters and the two maid servants.</p>
  </div>
  <div id="unit-two-slide-two"></div>
</body>

JS部分

var slidetwo = new Array( 
  "Brief background of who had which children and who got married to who.", 
  "- Include the Jewish year and the non - Jewish year ie BCE OR CE text two" 
);
var Speed = 100;
var Index = 0;
var ArrLength = slidetwo[0].length;
var ScrollAt = 20;
var TextPos = 0;
var Contents = '';
var Row;

function typewriter2() {
  Contents = ' ';
  Row = Math.max(0, Index-ScrollAt);
  var destination = document.getElementById("unit-two-slide-two");
  while ( Row < Index ) {
    Contents += slidetwo[Row++] + '<br />';
  }
  destination.innerHTML = Contents + slidetwo[Index].substring(0, TextPos) + "_";
  if ( TextPos++ == ArrLength ) {
    TextPos = 0;
    Index++;
    if ( Index != slidetwo.length ) {
      ArrLength = slidetwo[Index].length;
      setTimeout(typewriter2, 500); // 用函数引用替代字符串,更规范
    }
  } else {
    setTimeout(typewriter2, Speed); // 同上
  }
}

$(function() {
  $('#unit-two-slide-two').waypoint(function() {
    // 加个标记,避免用户反复滚动时重复触发动画
    if (!$(this.element).data('animated')) {
      typewriter2();
      $(this.element).data('animated', true);
    }
  }, { 
    offset: '90%', // 元素顶部进入视口90%时触发,可根据需求调整为百分比/像素
    // 移除horizontal: true,适配普通纵向滚动网页
  });
});

// 删掉全局的typewriter2()调用,避免页面加载直接启动动画

关键修改点说明

  1. 移除全局动画调用:删掉最后的typewriter2(),确保动画不会在页面加载时自动运行
  2. 补全Waypoint依赖:引入Waypoint核心JS文件,这是视口检测功能的基础
  3. 修正Waypoint配置:去掉horizontal: true,改用更直观的百分比offset配置
  4. 添加防重复触发逻辑:用data('animated')标记元素是否已执行动画,避免重复触发
  5. 规范setTimeout写法:把字符串形式的调用改成直接传函数引用,符合JS最佳实践

这样修改后,打字动画就只会在#unit-two-slide-two元素进入视口时才开始运行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:04:40