我想知道输入元素是否已更改,我了解到我可以在IE中收听onpropertychange
,在其他浏览器中收听oninput
。
这是我的代码:
var _addChangedProperty = function(input){
input.changed = false;
var oninput = function(){
this.changed = !!this.value;
if(this.changed){
this.style.color = "black";
}
};
input.onpropertychange = input.oninput = oninput;
};
现在我想将input.onpropertychange = input.oninput = oninput;
更改为addEventListerner
和attachEvent
,我需要检查是否支持onpropertychange
事件,我该怎么做(没有浏览器)检测)?
答案 0 :(得分:4)
您可以使用in
运算符进行检查:
"onpropertychange" in input
这种功能测试在旧版本的Firefox中不起作用,它为事件处理程序属性报告false
事件,该事件处理程序属性对应于存在的事件,但这不是问题,因为Firefox不会目前支持propertychange
事件,将来不太可能。
以下是一些背景资料:http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
另一点:您需要单独的函数来处理propertychange
和input
事件,因为在propertychange
处理程序中您需要检查它是否是value
属性那已经改变了。否则,您将最终处理对输入的任何属性的更改。
input.onpropertychange = function(evt) {
evt = evt || window.event;
if (evt.propertyName == "value") {
// Do stuff here
}
};