2011-07-11 81 views
5

这是一个有趣的一个,我只想在网页上输入一个秘密词语(不存在任何表单)时,我想在网站上显示某个div。 用JQuery完成这件事最简单的方法是什么?有没有插件? Thanx提前 欢呼Tabaluga如何查看JQuery,如果在浏览器中输入某个单词?

什么做
+0

如何/你在哪里希望用户键入这个词? –

+0

没有表格?你的意思是根本没有文字输入? – Johnny5

+0

所以你说的是,他们只是键入,而不是任何类型的文本框?排序的konami代码类型的东西? – Jeremy

回答

7
if (window.addEventListener) { 
     var kkeys = [], konami = "68,73,78,78,69,82"; //this spells dinner 
     window.addEventListener("keydown", function(e){ 
       kkeys.push(e.keyCode); 
       if (kkeys.toString().indexOf(konami) >= 0) { 
        // run code here  
        $("#text").hide().fadeIn("slow").html('Now the website will appear.'); 
       } 
     }, true); 
} 

您可以检查是什么字母:

if (window.addEventListener) { 
    window.addEventListener("keydown", function(e){ 
     $("#text").append(e.keyCode + " "); 
    }, true); 
} 
+0

伟大! Thanx很多:) – tabaluga

2

尝试使用js-Hotkey jquery plugin

$(document).bind('keydown', 's+e+c+r+e+t', fn); 

你也可能希望通过KonamiCodeWebsites检查看看它是如何工作的:

在这个网站上,您需要输入海啸代码(UP + UP + DN + DN + LFT + LFT + RGT + RGT + B + A)才能进入网站!

+0

很酷的插件!谢谢 – tabaluga

1

HTML:

<div style="display: none" class="secret">Correct password!</div> 

JS:

var pass="password"; 
var typed=""; 

$(document).keypress(
    function (e) { 
     typed += String.fromCharCode(e.which); 

     if (typed===pass) { 
      $('.secret').show(); 
     } 
    } 
); 

如果你熟悉JavaScript闭包你可以摆脱全局变量是这样的:

$(document).keypress((function(e) { 
    var pass = "password"; 
    var typed = ""; 

    return function(e) { 
     typed += String.fromCharCode(e.which); 

     console.log(typed); 
     if (typed === pass) { 
      $('.secret').show(); 
     } 
    }; 
})()); 
+0

谢谢你非常非常:) – tabaluga

0

听起来你需要听键盘事件。

$(document).ready(function(){ 
    var currentKey = 0; 
    var validKeyArray = [22,23,24]; //list of valid keys to listen to in order 
    $('body').keyup(function(event) { 
     if (event.keyCode == validKeyArray[currentKey]){ 
      currentKey ++; 
     } else { 
      currentKey = 0; 
     } 
     if (currentKey == validKeyArray.length){ 
      // SUCCESS! Do your magic div right here! 
      // console.log('SUCCESS!'); 
     } 

    }); 
}); 
+0

谢谢你非常非常:) – tabaluga

+0

没问题...我实际上认为成功的条件应该是'if(currentKey == validKeyArray.length-1)'哎呀! :-) –

+0

我觉得它''''''keyCode'''' camelcase –

0

这里是你可以做什么的例子:http://jsfiddle.net/Akkuma/CGmnw/

这是一个原型澄清。基本上这是做什么的,它维护的键码数组必须按顺序按下。然后,当检测到不正确的键或时间用完以输入时,它会增加检查并重置。

该原型提供了在错误的按键上以及经过一段时间后的重置。

+0

谢谢你,非常非常:) – tabaluga

2

纯JavaScript:

var typedWord = ''; 
window.addEventListener('keypress', function(e){ 
    var c = String.fromCharCode(e.keyCode); 
    typedWord += c.toLowerCase(); 
    if(typedWord.length > 4) typedWord = typedWord.slice(1); 
    if(typedWord == 'jogo') alert('JOGO'); 
}); 

http://codepen.io/rafaelcastrocouto/pen/xeGps

相关问题