如何在我的页面上添加特殊代码? (与Konami代码类似)

时间:2017-10-25 19:23:04

标签: javascript html

我正在寻找的与其他Konami代码问题不完全相同,用户键入某个代码(如konami代码),页面执行类似警报或加载不同页面的内容。我有一个主页面(index.html),其中包含几个段落。我希望默认隐藏一个段落,当用户键入konami代码(或某个键序列)时,我希望该段落出现。

<p id="hidden">TEXT TO BE HIDDEN BY DEFAULT</p

2 个答案:

答案 0 :(得分:0)

默认情况下隐藏它很简单,使用css,您可以将所有#hidden设置为display:none,从而使文字无法在页面上呈现

您可以使用document.body.addEventListener("keydown", callback);在javascript中聆听按键操作。然后,您可以将e.key存储在字符串中,并检查它是否等于回调中的字符序列。 e => {myString += e.key; if(myString === konamiCode) {使元素可见} }。要将元素设置为可见,您可以设置元素.style.display = block

答案 1 :(得分:0)

这应该不是一个问题,实现Konami代码的功能,虽然你说你只需要设置自己的特殊代码,但在检查之后你会做回调显示你的文本。

How to add konami code in a website based on html?复制并粘贴:

// a key map of allowed keys 
    var allowedKeys = {
      37: 'left',
      38: 'up',
      39: 'right',
      40: 'down',
      65: 'a',
      66: 'b'
    };
    
    // the 'official' Konami Code sequence Change this to you code
    var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];
    
    // a variable to remember the 'position' the user has reached so far.
    var konamiCodePosition = 0;
    
    // add keydown event listener
    document.addEventListener('keydown', function(e) {
      // get the value of the key code from the key map
      var key = allowedKeys[e.keyCode];
      // get the value of the required key from the konami code
      var requiredKey = konamiCode[konamiCodePosition];
    
      // compare the key with the required key
      if (key == requiredKey) {
    
        // move to the next key in the konami code sequence
        konamiCodePosition++;
    
        // if the last key is reached, activate cheats
        if (konamiCodePosition == konamiCode.length) {
          activateCheats();
          konamiCodePosition = 0;
        }
      } else {
        konamiCodePosition = 0;
      }
    });
    
    function activateCheats() {
      //Here our callback that will show your text
      document.getElementById("hidden").style.display = 'block';
    }
<p id="hidden" style="display:none">TEXT TO BE HIDDEN BY DEFAULT</p>