7

用onpropertychange,oninput事件解决onchange事件的不足

 3 years ago
source link: https://blogread.cn/it/article/576?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
您现在的位置首页 --> JavaScript --> 用onpropertychange,oninput事件解决onchange事件的不足

用onpropertychange,oninput事件解决onchange事件的不足

浏览:1207次  出处信息

    用onpropertychange,oninput事件解决onchange事件的不足.

    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=utf-8" /> 
<title>on用onpropertychange,oninput事件解决onchange事件的不足 by koyoz.com</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>
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK