转载自:http://my.oschina.net/tearlight/blog/191927
在网友Amin的帮助下,找到了一个兼容浏览器的方法(详情 http://dramin.duapp.com/?p=112)
主要是通过判断输入状态的改变,类似于onchange,IE9以上 、firefox、chrome等都支持了Html中的oninput事件,而IE6/7/8则可以通过onpropertychange事件来解决,但是IE6/7/8下如果input为disabled则事件无效,IE9+ FF opera11+,该事件用js改变值时不会触发,自动下拉框选值时不会触发,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
$(function(){
//初始化文本域
test();
var $test = $('#test');
function bindChangeHandler(input,fun) {
if("onpropertychange" in input) {//IE6、7、8,属性为disable时不会被触发
input.onpropertychange = function() {
debugger;
if(window.event.propertyName == "value") {
if(fun) {
fun.call(this,window.event);
}
}
}
} else {
//IE9+ FF opera11+,该事件用js改变值时不会触发,自动下拉框选值时不会触发
debugger;
input.addEventListener("input",fun,true);
}
}
//使用
bindChangeHandler($test[0],function(){
//alert(this.value);
debugger;
if (!("onpropertychange" in this)) {
this.style.height = 'auto';
this.scrollTop = 0; //防抖动
}
this.style.height = this.scrollHeight + 'px';
});
//$('#test').css({"height":"40px"});
});
function test()
{
if (!("onpropertychange" in $('#test'))) {
$('#test')[0].style.height = 'auto';
$('#test')[0].scrollTop = 0; //防抖动
}
$('#test')[0].style.height = $('#test')[0].scrollHeight + 'px';
}
</script>
</head>
<body>
<div><textarea id="test" autoHeight="true" style="overflow:hidden;resize:none;">
修改了 input:checkbox 或者 input:radio 元素的选择中状态, checked 属性发生变化。
修改了 input:text 或者 textarea 元素的值,value 属性发生变化。
修改了 select 元素的选中项,selectedIndex 属性发生变化。 ×
</textarea></div>
</body>
</html>