実現したいこと
フェードアウトというボタンを押すと、画像が1秒間かけて消えて、フェードアウトのボタンがフェードインのボタンに切り替わり、フェードインのボタンをクリックすると、画像が1秒かけて表示される仕組みを作りたいです。
前提
アニメーションをCSSのtransitionを使用せずにJavaScriptのopacityを用いて、作りたいです。
fade Animation関数を用いようと考えています。
発生している問題・エラーメッセージ
まだJavaScriptの知識が浅はかなので、素人でもわかるようにご教授いただけると幸いです。
該当のソースコード
html
1<!DOCTYPE html> 2<html> 3<head> 4 <meta charset="UTF-8"> 5 <title>lesson03 アニメーション2</title> 6 <link rel="stylesheet" type="text/css" href="base.css"> 7</head> 8<body> 9 <div id="wrapper"> 10 <div class="box"> 11 <button id="button" type="submit">フェードアウト</button> 12 <img id="image" src="./images/outsourcing.jpg" alt="サンプル画像"> 13 </div> 14 </div><!-- wrapper --> 15 16 <script> 17 const targettargetElement = document.getElementById("button"); 18 function fadeAnimation() { 19 targettargetElement.style.transition = "opacity 1s"; 20 let sw = 0 // 21 } 22 function fadeSwitch(){ 23 if(sw == 1){ 24 fadeIn(); 25 sw = 0; 26} 27 else if(sw == 0){ 28 fadeOut(); 29 sw = 1; 30} 31} 32 function fadeIn() { 33 targettargetElement.style.transition = "opacity 2s"; // 1 34 targettargetElement.style.opacity = "1"; // 1 35} 36 function fadeOut() { 37 targettargetElement.style.opacity = "0"; // 1 38} 39// setInterval fadeSwitch 2 40setInterval(fadeSwitch, 2000); 41 42 </script> 43</body> 44</html>
css
1@charset "UTF-8"; 2/* reset */ 3body, h1, h2, h3, h4, h5, h6, p, address, 4ul, ol, li, dl, dt, dd, img, form, table, tr, th, td { 5 margin: 0; 6 padding: 0; 7 border: none; 8 font-style: normal; 9 font-weight: normal; 10 font-size: 100%; 11 text-align: left; 12 list-style-type: none; 13 border-collapse: collapse; 14} 15 16textarea { font-size: 100%; vertical-align:middle;} 17img { border-style: none; display: block; } 18hr { display: none; } 19em{font-style: normal} 20input{line-height:auto;vertical-align:middle;} 21strong.more{color:#c30} 22a{text-decoration: none;} 23 24html { 25 26} 27 28body { 29 font-family:'ヒラギノ角ゴ Pro W3','Hiragino Kaku Gothic Pro','メイリオ',Meiryo,'MS Pゴシック',sans-serif; 30} 31 32* { 33 -webkit-box-sizing: border-box; 34 -moz-box-sizing: border-box; 35 -o-box-sizing: border-box; 36 -ms-box-sizing: border-box; 37 box-sizing: border-box; 38} 39 40/* 上の部分は気にせずここから書く */ 41#wrapper { 42 height: 100vh; 43 display: flex; 44 justify-content: center; 45 align-items: center; 46} 47 48.box { 49 display: flex; 50 flex-direction: column; 51} 52 53#button { 54 width: 200px; 55 height: 60px; 56 background-color: #fdd; 57 border: none; 58 margin: 0 auto 20px; 59 cursor: pointer; 60} 61 62#image { 63 width: 300px; 64 opacity: 1; 65} 66
試したこと
Chromeでopacity JavaScriptについて調べ、コードを打ってみたりしたが、反応せず、困っています。
