onchange在用於文本框輸入框時,有一個明顯的不足. 事件不會隨着文字的輸入而觸發,而是等到文本框失去焦點(onblur)時纔會觸發. 也就是沒有即時性!
在IE下,可以用onpropertychange來代替onchange事件,當文本框有任何變化時,能立即觸發此事件.
這樣一來問題就解決了.
那其他瀏覽器呢,onpropertychange可是IE的專利. 接下來就是oninput事件了.
但是oninput有個詭異,必須用addEventListener的方式來綁定事件.否則無效.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>on用onpropertychange,oninput事件解決onchange事件的不足</title>
<style type="text/css">
*{font-size:14px;font-family:'Comic Sans MS', Verdana}
body {margin-left:20px}
</style>
</head>
<body>
<p>使用onchange事件: </p>
<input type="text" id="txt1" />
<p>使用onpropertychange/oninput事件: </p>
<input type="text" id="txt2" />
<p>結果:</p>
<input type="text" id="txt" />
<script type="text/javascript">
var $ = function(o) {
return document.getElementById(o)
};
$('txt1').onchange = function() {
$('txt').value = this.value;
}
$('txt2').onpropertychange = function() {
$('txt').value = this.value;
}
if (window.addEventListener) {
$('txt2').addEventListener('input', function() {$('txt').value = this.value}, false);
}
</script>
</body>
</html>
(本文轉載自腳本之家)