Menu
CoddyTech

滚动时为元素添加动画

本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 19 课,共 27 课。

有时,我们希望元素在滚动进入视口时执行动画(淡入、滑入、缩放等)。
通常的做法是检查元素是否在屏幕上可见,然后添加一个类来触发 CSS 动画或过渡效果。

首先,我们来创建一个简单的 HTML 元素:

<div class="animate-on-scroll">This element will animate when scrolled into view</div>

接下来,为动画添加 CSS:

.animate-on-scroll {
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.5s ease, transform 0.5s ease;
}

.animate-on-scroll.visible {
  opacity: 1;
  transform: translateY(0);
}

现在,我们来创建一个 JavaScript 函数,检测元素何时滚动到视口中。由于元素可能不止一个,我们用 forEach 遍历它们,并检查每个元素相对于视口的位置。

function checkScroll() {
  const elements = document.querySelectorAll('.animate-on-scroll');
  
  elements.forEach(element => {
    // 获取元素相对于视口的位置
    const position = element.getBoundingClientRect();
    
    // 如果元素在视口内
    if(position.top < window.innerHeight) {
      element.classList.add('visible');
    }
  });
}

// 滚动时运行
window.addEventListener('scroll', checkScroll);

// 页面加载时运行一次
checkScroll();

当带有 animate-on-scroll 类的元素进入视口时,脚本会添加 visible 类,从而触发动画。

challenge icon

挑战

简单

在循环内部,创建一个if 语句。

  1. 条件应检查:元素的顶部位置是否小于 window.innerHeight - 50。
  2. 如果条件为 true,使用 .classList.add("active") 将 active 类添加到该元素。

这样,每当元素滚动到视野内(距离屏幕底部 50px 以内)时,它就会平滑地淡入。

亲手试试

<!DOCTYPE html>
<html>
<head>
  <title>Scroll Animation Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Discover the Beauty of Nature</h1>
    <p>Scroll down to reveal the magic</p>
  </header>

  <div class="container">
    <div class="fade-in card">
      <h2>Mountains</h2>
      <p>Standing tall and timeless, mountains remind us of strength and stability.</p>
    </div>

    <div class="fade-in card">
      <h2>Forests</h2>
      <p>Forests are the lungs of our planet, offering peace and endless green beauty.</p>
    </div>

    <div class="fade-in card">
      <h2>Rivers</h2>
      <p>Calm or powerful, rivers flow endlessly, connecting life along their paths.</p>
    </div>

    <div class="fade-in card">
      <h2>Deserts</h2>
      <p>Silent and vast, deserts teach us resilience and the value of every drop of water.</p>
    </div>

    <div class="fade-in card">
      <h2>Oceans</h2>
      <p>The oceans cover most of our Earth, a mysterious world full of wonder and life.</p>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

JavaScript 实战中的所有课

自己练习: Web 在线编辑器