发现一个问题,在input/textarea中若是是鼠标粘贴内容进去,发现判断不了value的改变,html代码以下: javascript
<!doctype html> <html> <head> <meta charset="utf-8"> <title>判断粘贴</title> <script type="text/javascript" src="../jquery.js"></script> </head> <body> <textarea name="" id="test" cols="30" rows="10"></textarea> </body> </html>
我写的监听方法:(使用了jquery) html
var $test = $('#test'); $test.on('keyup',function(){ console.log('keyup__'+this.value); }) .on('mouseup',function(){ console.log('mouseup__'+this.value); }) ;
以上方法只能判断键盘的快捷键粘贴 若是是鼠标粘贴就失效了
后面在网友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改变值时不会触发,自动下拉框选值时不会触发,代码以下: java
function bindChangeHandler(input,fun) { if("onpropertychange" in input) {//IE六、七、8,属性为disable时不会被触发 input.onpropertychange = function() { if(window.event.propertyName == "value") { if(fun) { fun.call(this,window.event); } } } } else { //IE9+ FF opera11+,该事件用js改变值时不会触发,自动下拉框选值时不会触发 input.addEventListener("input",fun,false); } } //使用 bindChangeHandler($test[0],function(){ alert(this.value); });