有趣的问题 - 例如它发生在 IE 中,但不是 Chrome。这是我在 Chrome 和 IE 中测试过的解决方案(似乎可行)。
扩展版:
页眉中的脚本:
<script>
var buff; //Must have global scope
var input = document.getElementById("testinput"); //Defined here to save cpu (instead of on every key press).
function CheckPreBuff(e)
{
var ev = window.event ? event : e; //Get the event object for IE or FF
var unicode = (typeof(ev.keyCode) != "undefined")? ev.keyCode : ev.charCode;
if(unicode != 27) buff = input.value; //The 'escape' key has a unicode value of 27
else input.value = buff; //Only set the input contents when needed, so not to waste cpu.
}
</script>
'testinput' 是我们禁用转义的输入。测试输入 html 如下:
<input id="testinput" onkeypress="CheckPreBuff();" onkeyup="CheckPreBuff();" type="text"/>
注意“onkeyup”和“onkeypress”都被使用了——技术上只需要“onkeyup”,尽管使用“onkeypress”可以防止文本框在按下转义键时暂时变为空白。
手动缩小 + 错误预防 + 支持多输入(如果您愿意)
标题中的脚本:
<script>
var buff = [];
function InitCPB(obj){if(typeof(obj)=="undefined")return;buff[0]=obj;buff[1]="";obj.onkeypress=CPB;obj.onkeyup=CPB;}
function CPB(e){if(typeof((buff[0]))=="undefined")return;var ev=window.event?event:e;(((typeof(ev.keyCode)!="undefined")?ev.keyCode:ev.charCode)!=27)?buff[1]=(buff[0]).value:(buff[0]).value=buff[1];}
</script>
testinput html 标签(虽然不再需要 id):
<input onfocus="InitCPB(this);" type="text"/>
这两种方法都会在按下下一个键之前保留文本输入的副本,如果按下的键是 'escape',unicode 27,则将上一个文本输入放回文本框(这是有区别的,所以该脚本不会在每次按键时给浏览器增加太多负载)。
第二个版本允许在同一页面上禁用转义键的多个文本输入 - 只要它们具有如上所述的 onFocus 属性设置(多个元素不会相互干扰)。它还检查传递给它的对象是否已定义,以防止意外错误实现导致 IE 心脏病发作!
我希望这会有所帮助。