【发布时间】:2018-06-04 11:51:39
【问题描述】:
<input type="text" id="search" size="25" autocomplete="off"/>
我知道这是与
onkeydown="if (event.keyCode == 27)
【问题讨论】:
标签: javascript html css
<input type="text" id="search" size="25" autocomplete="off"/>
我知道这是与
onkeydown="if (event.keyCode == 27)
【问题讨论】:
标签: javascript html css
声明一个按键被按下时调用的函数:
function onkeypressed(evt, input) {
var code = evt.charCode || evt.keyCode;
if (code == 27) {
input.value = '';
}
}
以及对应的标记:
<input type="text" id="search" size="25" autocomplete="off"
onkeydown="onkeypressed(event, this);" />
【讨论】:
keyCode。所有主流浏览器都有keyCode,因此无需检查charCode,无论如何在所有当前浏览器中它都是零或未定义。
<input type="text" value="" onkeyup="if ( event.keyCode == 27 ) this.value=''" />
这应该可行。
【讨论】:
function keyPressed(evt) {
if (evt.keyCode == 27) {
//clear your textbox content here...
document.getElementById("search").value = '';
}
}
然后在你的输入标签中...
<input type="text" onkeypress="keyPressed(event)" id="search" ...>
【讨论】:
onkeypress 不检测转义、shift、箭头键等。必须是onkeydown 或onkeyup。
$('input[type=text]').each(function (e) {
$(this).keyup(function (evt) {
var code = evt.charCode || evt.keyCode;
if (code == 27) {
$(this).val('');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" autofocus value="input data" placeholder="ESC button clear" style="padding:5px;">
<p>Hit esc button to see result</p>
【讨论】: