← 動的パーツギャラリーへ戻る

パーツ番号 02-09-08 ・ JavaScript使用

乱数スロットテキスト

各文字が高速で乱数記号に入れ替わりながら1文字ずつ確定していくスロットマシン風演出です。WordPressのくじ引き・抽選キャンペーンページの当選ワード表示に活用できます。

js

プレビュー

ソースコード

HTML

<div class="d02-09-08-board"></div>

CSS

.d02-09-08{background:#161616}
        .d02-09-08-board{display:flex;gap:5px}
        .d02-09-08-cell{width:32px;height:44px;background:#1f1f1f;color:#fbbf24;
          font-family:ui-monospace,Menlo,monospace;font-weight:800;font-size:24px;
          display:flex;align-items:center;justify-content:center;border-radius:4px;
          border:1px solid #3a3a3a;box-shadow:inset 0 -2px 0 rgba(0,0,0,.6)}

JavaScript

(function(){
        var board=document.querySelector('#item-02-09-08 .d02-09-08-board');
        var words=['WIN!','LUCKY','BONUS','SEVEN'];
        var glyphs='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var len=5,cells=[];
        for(var i=0;i<len;i++){var c=document.createElement('div');c.className='d02-09-08-cell';c.textContent=' ';board.appendChild(c);cells.push(c);}
        var reduce=window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        function pad(w){return (w+'     ').slice(0,len);}
        if(reduce){
          cells.forEach(function(cell,i){cell.textContent=pad(words[0])[i];});
          return;
        }
        var wi=0;
        function show(word){
          word=pad(word);
          cells.forEach(function(cell,i){
            var steps=8+i*3,n=0;
            var t=setInterval(function(){
              cell.textContent=word[i]===' '?' ':glyphs[Math.floor(Math.random()*glyphs.length)];
              n++;
              if(n>=steps){clearInterval(t);cell.textContent=word[i];}
            },55);
          });
        }
        show(words[0]);
        setInterval(function(){wi=(wi+1)%words.length;show(words[wi]);},3000);
      })();

クラス名 .d02-09-08 は本ライブラリ内での識別用です。複数のパーツを同じページで使う場合は、重複しないよう名前を変更してください。