如何禁用除文本框之外的所有页面上的键

时间:2017-06-03 02:53:46

标签: javascript java html web key

在我的网站上,我使用了以下代码:

  <script type='text/javascript'>
    document.onkeydown = function (e) 
    {
    return false;
    }
  </script>

  <script type='text/javascript'>
   document.onkeyup = function (e) 
   {
   return false;
   }
 </script>

但是,在我的网站标题中,我希望用户能够输入聊天文本框而无法在其他地方输入。聊天文本框的代码是:

  <div style="-moz-user-select: none; -webkit-user-select: none; -ms-user-
  select:none; user-select:none;-o-user-select:none;" unselectable="on"
   onselectstart="return false;" onmousedown="return false;">

  <script type='text/javascript'>
  document.onkeydown = function (e) 
  {
  return true;
  }
  </script>

  <script type='text/javascript'>
  document.onkeyup = function (e) 
  {
   return true;
  }
  </script>

 <script type="text/javascript" async> ;
 (function(o,l,a,r,k,y)
{if(o.olark)return; 
r="script";y=l.createElement(r);r=l.getElementsByTagName(r)[0]; 
y.async=1;y.src="//"+a;r.parentNode.insertBefore(y,r); y=o.olark=function()
{k.s.push(arguments);k.t.push(+new Date)}; y.extend=function(i,j)
{y("extend",i,j)}; y.identify=function(i){y("identify",k.i=i)}; 
y.configure=function(i,j){y("configure",i,j);k.c[i]=j}; k=y._={s:[],t:[+new 
Date],c:{},l:a}; })(window,document,"static.olark.com/jsclient/loader.js");
/* custom configuration goes here (www.olark.com/documentation) */
olark.identify('2624-366-10-5413');
</script>

<script type='text/javascript'>
 document.onkeydown = function (e) {
     return false;

 }


 </script>
 <script type='text/javascript'>
   document.onkeyup = function (e) 
 {
   return false;
 }
 </script>

这是我到目前为止编写的完整代码。

1 个答案:

答案 0 :(得分:0)

看一下 JSFIDDLE

JAVASCRIPT: -

    document.onkeyup = function(e){
    console.log(e.target);
  if(e.target.tagName == "INPUT"){
   console.log(e.target.type);
    if(e.target.type == "text"){
        alert("Can press the key");
        return true;
    }
  }
 alert("Can't press the key"); 
 return false;
}

document.onkeydown = function(e){
 if(e.target.tagName == "INPUT"){
   console.log(e.target.type);
    if(e.target.type == "text"){
        alert("Can press the key");
        return true;
    }
  }
 alert("Can't press the key"); 
 return false;
}

HTML: -

    <input type="text" />
<textarea></textarea>