【问题标题】:How to disable keys on all of the page except for text boxes如何禁用除文本框以外的所有页面上的键
【发布时间】:2017-09-10 00:05:27
【问题描述】:

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

  <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>

这就是我目前所写的完整代码。

【问题讨论】:

  • 你说的别处是什么意思?页面上是否还有其他不希望他们使用的输入字段?如果是这样,他们为什么会在那里?如果无法删除它们,您就不能禁用它们吗?
  • @BSMP 我希望它们在除聊天之外的所有地方都被禁用。
  • @javamaster 是的,我也不明白你的意思。如果不使用它们,为什么您的页面上还有其他输入字段。请不要说你用输入来设计你的页面。
  • 您可以使用 e.target 属性,它会为您提供您按下键的元素。

标签: javascript java html web key


【解决方案1】:

看看这个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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多