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

Vue中Scroll animations不生效:IntersectionObserver未触发观测

问题原因及解决方案

你的代码存在两个核心问题,导致IntersectionObserver无法正常触发动画:

1. DOM元素获取时机错误

你直接在<script>根节点执行document.querySelectorAll(".hidden"),此时Vue组件还未完成挂载,DOM元素尚未渲染到页面,因此无法获取到目标元素,IntersectionObserver也就无法绑定到任何元素上。

2. CSS语法错误

background-color: 131313;缺少十六进制颜色的#前缀,正确写法应为background-color: #131313;,虽然这不是动画失效的直接原因,但会导致页面样式异常。


修正后的完整代码

<template>
  <section class="hidden">
    <h1>Title</h1>
    <p>Some text</p>
  </section>
  <section class="hidden">
    <h2>More text</h2>
  </section>
</template>

<style scoped>
* {
  background-color: #131313;
  padding: 0;
  margin: 0;
  color: white; /* 新增:让文字在深色背景下可见 */
}

section {
  display: grid;
  place-items: center;
  align-content: center;
  min-height: 100vh;
}
.hidden {
  opacity: 0;
  transition: all 1s;
}
.show {
  opacity: 1;
}
</style>

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      entry.target.classList.toggle("show", entry.isIntersecting);
    });
  });

  const hiddenElements = document.querySelectorAll(".hidden");
  hiddenElements.forEach((el) => observer.observe(el));
});
</script>

额外说明

  • 使用Vue 3推荐的<script setup>语法,配合onMounted钩子确保DOM渲染完成后,再执行元素查询和Observer绑定操作。
  • 用classList.toggle简化了类名添加/移除的逻辑,代码更简洁。
  • 如果是Vue 2项目,可调整为如下结构:
export default {
  mounted() {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        entry.target.classList.toggle("show", entry.isIntersecting);
      });
    });

    const hiddenElements = document.querySelectorAll(".hidden");
    hiddenElements.forEach((el) => observer.observe(el));
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:42:46