実現したいこと
- Vueでページをスクロールしてきて要素が画面内に十分入ったときにふわっとフェードインさせたい。
発生している問題
画面内に入る前にフェードインアニメーションが行われてしまい、画面内に入ったときにはopacity: 1ですでに表示されてしまっている。
該当のソースコード
App.vue
1<template> 2 <div> 3 <br> 4 <br> 5 <br> 6 //<br>省略 7 8 <h1 class="fade-in-on-scroll">Hello World!</h1> 9 </div> 10</template> 11 12<style> 13.fade-in-on-scroll { 14 opacity: 0; 15 animation-name: fade-in-on-scroll; 16 animation-duration: 1s; 17 animation-delay: 0s; 18 animation-fill-mode: forwards; 19} 20 21.fade-in-on-scroll-active { 22 opacity: 1; 23} 24 25@keyframes fade-in-on-scroll { 26 from { 27 opacity: 0; 28 transform: translateY(20px); 29 } 30 to { 31 opacity: 1; 32 transform: translateY(0); 33 } 34} 35</style> 36 37<script lang="ts"> 38export default { 39 mounted() { 40 window.addEventListener("scroll", this.handleScroll); 41 this.handleScroll(); 42 }, 43 destroyed() { 44 window.removeEventListener("scroll", this.handleScroll); 45 }, 46 methods: { 47 handleScroll() { 48 const el = this.$el.querySelector(".fade-in-on-scroll"); 49 const elTop = el.getBoundingClientRect().top; 50 const windowHeight = window.innerHeight; 51 const yOffset = 100; 52 if (elTop - windowHeight + yOffset <= 0) { 53 el.classList.add("fade-in-on-scroll-active"); 54 window.removeEventListener("scroll", this.handleScroll); 55 } 56 } 57 } 58}; 59</script>
試したこと
Vueのtransitionなども試してみたのですが最近のWebサイトでよく見るスクロールエフェクトの「画面内に入ったときにふわっと表示させる」ことがうまくいかず、困っています。
補足情報(FW/ツールのバージョンなど)
vue 3.2.47

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/03/25 01:23