前提・実現したいこと
画面が指定の位置に来た時、<span>で囲んだ文字が下から上がってくるアニメーションを実装したいんですが、スクロールするたびにアニメーションが適応されてしまうのはなぜでしょうか。
該当のソースコード
HTML
1 <main> 2 <div class="text-animation">テキストテキストテキスト</div> 3 <div class="text-animation">TextText TextText</div> 4 </main>
CSS
1/* ====== header ====== */ 2header { 3 height: 100vh; 4} 5 6/* ====== main ====== */ 7main { 8 height: 100vh; 9 background: black; 10 display: flex; 11 justify-content: center; 12 align-items: center; 13 flex-flow: column; 14} 15 16.text-animation { 17 color: white; 18 font-size: 50px; 19} 20 21.text-animation span { 22 display: inline-block; 23} 24 25@keyframes activeText { 26 from { 27 opacity: 0; 28 transform: translateY(100%); 29 } 30 to { 31 opacity: 1; 32 transform: none; 33 } 34} 35 36.text-animaiton > span { 37 overflow: hidden; 38} 39 40.text-animation > span > span { 41 animation: activeText 1s backwards; 42}
'use strict'; function slideText(){ const textAnimation = document.querySelectorAll('.text-animation'); for(let i = 0; i < textAnimation.length; i++) { const textDivition = textAnimation[i], texts = textDivition.textContent, textArray = []; textDivition.textContent = ""; for (let j = 0; j < texts.split("").length; j++) { if(texts.split("")[j] === " ") { textArray.push(" ") } else { textArray.push('<span><span style="animation-delay: ' + (j * .1) + 's;">' + texts.split("")[j] + '</span></span>') } } for(let k = 0; k < textArray.length; k++) { textDivition.innerHTML += textArray[k] } } } const mainElement = document.getElementsByTagName('main'); document.addEventListener('scroll', function(){ for(let i = 0; i < mainElement.length; i++) { const mainDistance = mainElement[i].getBoundingClientRect().top + mainElement[i].clientHeight *.5 if(window.innerHeight > mainDistance) { slideText(); } } });
補足情報(FW/ツールのバージョンなど)
dynabook V72/JLE
型番:PV82JLECNRDQE
あなたの回答
tips
プレビュー