2016-02-05 57 views
3

我正在將一個Konami復活節彩蛋放入我的網站以供踢腿;你輸入Konami密碼,它會播放街頭霸王的誇張聲音,背景中的歌舞伎面具上的眼睛會亮起一秒鐘。我該如何獲得這個Javascript函數來正確迭代?

它有效...有點。我遇到了問題。輸入Konami代碼後,每次用戶按下一個鍵時,上述效果都會迭代。這並不意味着要這樣做。每次用戶輸入完整的代碼時,我只想立即關閉效果。

還有另一個更小的呃逆,會很好解決。通過簡單地將初始背景切換爲具有期望效果的一個,實際上使面具的眼睛發亮。但是,第一次完成時,頁面會在第二個背景加載時閃爍,但後續迭代中不會有閃光。我的想法是將第二個背景加載爲HTML圖像,並將其可見性設置爲隱藏,但這並不起作用。

<script> 
     function PlaySound(path) 
     { 
      var audioElement = document.createElement('audio'); 
      audioElement.setAttribute('src', path); 
      audioElement.play(); 
     } 
     function resetBackground() 
     { 
      document.body.style.backgroundImage = "url('onics.png')"; 
     } 
     function flashBackground() 
     { 
      document.body.style.backgroundImage = "url('onics_red.png')"; 
      setTimeout(resetBackground, 830); 
     } 
     if(window.addEventListener) 
     { 
      var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65"; 
      window.addEventListener("keydown",function(e) 
      { 
      kkeys.push(e.keyCode); 
      if(kkeys.toString().indexOf(konami)>=0) 
       { 
        PlaySound('hadouken.wav'); 
        flashBackground(); 
       } 
      },true); 
     } 
    </script> 

回答

3

您需要的kkeys陣列復位:

if(window.addEventListener) 
    { 
     var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65"; 
     window.addEventListener("keydown",function(e) 
     { 
     kkeys.push(e.keyCode); 
     if(kkeys.toString().indexOf(konami)>=0) 
      { 
       kkeys = []; 
       PlaySound('hadouken.wav'); 
       flashBackground(); 
      } 
     },true); 
    } 
+0

這樣做。謝謝,jcubic。 –

1

您可以添加一個標誌

<script> 
    var konamiPlayed = false; 
    function PlaySound(path) 
    { 
     var audioElement = document.createElement('audio'); 
     audioElement.setAttribute('src', path); 
     audioElement.play(); 
    } 
    function resetBackground() 
    { 
     document.body.style.backgroundImage = "url('onics.png')"; 
     konamiPlayed = false; 
    } 
    function flashBackground() 
    { 
     document.body.style.backgroundImage = "url('onics_red.png')"; 
     setTimeout(resetBackground, 830); 
    } 
    if(window.addEventListener) 
    { 
     var kkeys=[],konami="38,38,40,40,37,39,37,39,66,65"; 
     window.addEventListener("keydown",function(e) 
     { 
      if (!konamiPlayed) { 
       kkeys.push(e.keyCode); 
       if(kkeys.toString().indexOf(konami)>=0) 
       { 
        konamiPlayed = true; 
        PlaySound('hadouken.wav'); 
        flashBackground(); 
       } 
      } 
     },true); 
    } 
</script> 

編輯:

而對於小問題,我想這是因爲瀏覽器加載圖像只有當你問它。所以,第一次需要一些時間。

+0

我很感激,Gwendal。不過,這引入了一個不同的問題。當我使用這個腳本時,它只會播放一次,句號。每次輸入代碼時,我都希望它播放一次。所以,當我的原始代碼在輸入代碼時進行播放時,以及之後的每次擊鍵(不好)時,無論代碼輸入多少次,此代碼只會播放一次。 –

+0

@AdamFeoras我的不好,我沒有正確理解你的問題。 jcubic給了一個更好的答案 – Gwendal

+0

我仍然很感激你抽出週五早上的時間來幫助我。 –

相關問題