Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

php - How do I capture keystrokes on the web?

Using PHP, JS, or HTML (or something similar) how would I capture keystokes? Such as if the user presses ctrl+f or maybe even just f, a certain function will happen.

++++++++++++++++++++++++EDIT+++++++++++++++++++ Ok, so is this correct, because I can't get it to work. And I apologize for my n00bness is this is an easy question, new to jQuery and still learning more and more about JS.

<script>    
var element = document.getElementById('capture');
    element.onkeypress = function(e) { 
       var ev = e || event;
       if(ev.keyCode == 70) {
          alert("hello");
       }
    }
</script>
<div id="capture">
Hello, Testing 123
</div>

++++++++++++++++EDIT++++++++++++++++++

Here is everything, but I can't get it to work:

<link rel="icon" href="favicon.ico" type="image/x-icon">
<style>
* {
margin: 0px
}  

div {
    height: 250px;
    width: 630px;
    overflow: hidden;
    vertical-align: top;
    position: relative;
    background-color: #999;
}
  iframe {
    position: absolute;
    left: -50px;
    top: -130px;
  }
</style>
<script>
document.getElementsByTagName('body')[0].onkeyup = function(e) { 
   var ev = e || event;
   if(ev.keyCode == 70 && ev.ctrlKey) { //control+f
      alert("hello");
   }
}
</script>
<div id="capture">
Hello, Testing 123<!--<iframe src="http://www.pandora.com/" scrolling="no" width="1000" height="515"frameborder="0"></iframe>-->
</div>

+++EDIT+++

Thanks to Jacob, I had thought that I had it fixed, but when I tried it in FF and IE (currently using chrome, which did work) it did not work. This script is just going to be for a personal page that only I will see, so it is not the biggest deal, but for future reference, I would just like to know why this is not working in either IE or FF.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, the only way to do this would be through JavaScript, and you'd do so like this:

window.onload = function() {
   document.getElementsByTagName('body')[0].onkeyup = function(e) { 
      var ev = e || event;
      if(ev.keyCode == 70) {//&& ev.ctrlKey) {
         //do something...
      }
   }
};

To find out the specific key code you want, see this article: http://www.webonweboff.com/tips/js/event_key_codes.aspx

jsFiddle example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...