LoginSignup
0
1

More than 1 year has passed since last update.

ボタンを押すとランダム関数が走り、画像が遷移する方法

Posted at

こんにちは、ブヒブヒです。
自分が学んだ内容をメモのつもりで書いていきます。

現在絶賛javascriptを勉強中です。
課題でjavascriptをルーレットを作ったので共有します。
ルーレットを作るには「HTML」「CSS」「javascript」「DOM」使います。

HTML
画像
      <div id="target"></div>
      <div id="main">
        <img src="lunch/main.jpg" alt="おれのランチ" class="img_size">
      </div>
      <div id="slot">
        <img src="lunch/sushi.jpg" alt="寿司" class="hidden img_size">
      </div>


ボタン
      <button class="btn-blue" id="start_btn">start</button>  
      <button class="btn-red" id="stop_btn">stop</button>


CSS
      .hidden {
      display: none;
      }


javascript
配列を作成
      const lunch_lists = [
    {
        title: "久兵衛",
        image: "lunch/sushi.jpg"
    },
    {
        title: "叙々苑",
        image: "lunch/jojoen.jpg"
    },
    {
        title: "オレ!!",
        image: "lunch/ore.jpg"
    }

   ];


DOM 
    const target = document.getElementById('target'); 
    const start_btn = document.getElementById('start_btn'); 
    const main = document.getElementById('main');
    const slot = document.getElementById('slot').firstElementChild;
    
    
    let timer_id = 0; 
    

ランダム関数
    function randomImg(lunch_lists) {
        const rand = Math.floor(Math.random() * lunch_lists.length);
        slot.setAttribute('src', lunch_lists[rand].image); 
    };
    

スタートボタン
    start_btn.addEventListener( 'click', function(e) {
    
        main.classList.add('hidden');
        slot.classList.remove('hidden');
        timer_id = setInterval(() => {
          randomImg(lunch_lists);  
        }, 1000);
    });

クリックすると、ランダムで画像が遷移します。

1.スタートボタンを押すと
2.domでidのmain,slotを取得
3.main.classList.add('hidden'); の画像を隠す
4.slot.classList.remove('hidden'); で隠れていた画像を見せる。
   (CSSで当初から画像を隠している)
5.timer_id = setInterval(() => {randomImg(lunch_lists); }, 1000); });
    で1秒ずつ、ランダムに遷移するように関数を作成


①firstElementChild  「slot」の子要素を取得する つまり下記を取得する

     <img src=".....jpg" alt="寿司" class="hidden img_size">

②識別の番号

let timer_id = 0; 

③setAttribute

setAttribute(name(属性の名前を文字列), value(属性に設定したい値));

次は、stop方法の記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1