実現したいこと
- 1つのボタンを使って、画像のフェードイン、フェードアウトのアニメーションを切り替えられるようにしたい
前提
下図の画像を「ファードアウト」ボタンを押したらフェードアウトさせ
再度ボタンを押したらフェードインするように実装したいです。
発生している問題・エラーメッセージ
エラーは発生していません。
フェードアウトの状態からボタンを押しても、何も変わらない状態です。
該当のソースコード
CSS
1#wrapper { 2 height: 100vh; 3 display: flex; 4 justify-content: center; 5 align-items: center; 6} 7 8.box { 9 display: flex; 10 flex-direction: column; 11} 12 13#button { 14 width: 200px; 15 height: 60px; 16 background-color: #fdd; 17 border: none; 18 margin: 0 auto 20px; 19 cursor: pointer; 20} 21 22#image { 23 width: 300px; 24 opacity: 1; 25}
HTML
1<div id="wrapper"> 2 <div class="box"> 3 <button id="button" type="submit">フェードアウト</button> 4 <img id="image" src="./images/outsourcing.jpg" alt="サンプル画像"> 5 </div> 6</div><!-- wrapper -->
JavaScript
1 <script> 2 window.addEventListener('DOMContentLoaded', function fadeAnimation(e){ 3 e.preventDefault(); 4 // if判定用 5 let isCrick = false; 6 7 let isButton = document.querySelectorAll('#button')[0] 8 let fadeImage = document.querySelectorAll('#image')[0] 9 isButton.addEventListener('click',()=>{ 10 if(isCrick){ 11 //二重処理防止 12 return false; 13 }else if( isButton.textContent = 'フェードアウト' ){ 14 // ボタンの文字を変える 15 isButton.textContent = 'フェードイン'; 16 // 1クリック時 17 isCrick = true; 18 19 fadeImage.animate( 20 [ 21 //透過度(1:初期状態→0:完全に透過) 22 {opacity: 1}, 23 {opacity: 0} 24 ], 25 { 26 // アニメーション時間 27 duration: 2000, 28 // 最後の状態で停止 29 fill: 'forwards' 30 }) 31 }else{ 32 // ボタンの文字を変える 33 isButton.textContent = 'フェードアウト'; 34 // 1クリック時 35 isCrick = true; 36 37 fadeImage.animate( 38 [ 39 //透過度(1:初期状態→0:完全に透過) 40 {opacity: 0}, 41 {opacity: 1} 42 ], 43 { 44 // アニメーション時間 45 duration: 2000, 46 // 最後の状態で停止 47 fill: 'forwards' 48 }) 49 50 } 51 52 53 } 54 ) 55 }); 56 </script> 57
試したこと
透明度の変更にclasslistを使用してみたりしましたが、animationとは一緒に使えないとわかりました。

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