要实现滚动动画,可以使用 CSS 中的 @keyframesanimation 属性,以及 JavaScript 中的 scroll 事件。

首先,在 HTML 中添加一个用于滚动的容器,例如:

<div id='scroll-container'>
  <p>这是一段需要滚动的文本。</p>
</div>

然后,在 CSS 中定义动画效果:

@keyframes scroll {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-100%);
  }
}

#scroll-container p {
  animation: scroll 6s linear infinite;
}

这里定义了一个名为 scroll 的动画,从初始状态的 translateY(0) 向上滚动到 translateY(-100%),持续时间为 6 秒,使用线性动画效果,无限循环。

最后,在 JavaScript 中监听滚动事件,当滚动到指定位置时触发动画:

window.addEventListener('scroll', function() {
  var scrollPosition = window.scrollY;
  var targetPosition = document.getElementById('scroll-container').offsetTop;
  if (scrollPosition > targetPosition) {
    document.getElementById('scroll-container').classList.add('scrolling');
  } else {
    document.getElementById('scroll-container').classList.remove('scrolling');
  }
});

这里通过计算滚动位置和目标位置,判断是否滚动到了指定位置,然后添加或移除一个名为 scrolling 的类,用于触发动画。

最后,完整的 HTML 代码如下:

<!DOCTYPE html>
<html>
<head>
  <title>滚动动画</title>
  <style>
    @keyframes scroll {
      from {
        transform: translateY(0);
      }
      to {
        transform: translateY(-100%);
      }
    }
    
    #scroll-container p {
      animation: scroll 6s linear infinite;
    }
    
    #scroll-container.scrolling p {
      animation-play-state: running;
    }
    
    #scroll-container p:hover {
      animation-play-state: paused;
    }
  </style>
</head>
<body>
  <div id='scroll-container'>
    <p>这是一段需要滚动的文本。</p>
  </div>
  <script>
    window.addEventListener('scroll', function() {
      var scrollPosition = window.scrollY;
      var targetPosition = document.getElementById('scroll-container').offsetTop;
      if (scrollPosition > targetPosition) {
        document.getElementById('scroll-container').classList.add('scrolling');
      } else {
        document.getElementById('scroll-container').classList.remove('scrolling');
      }
    });
  </script>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/miYC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录