开发者

How to test if onpropertychange is supported or not?

I'd like to know if an input element has changed, I learned that I can listen to onpropertychange in IE and oninput in other browsers.

Here is my code:

开发者_如何学C
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;
};

Now I'd like to change input.onpropertychange = input.oninput = oninput; to addEventListerner and attachEvent, I need to check if onpropertychange event is supported, how could I do this (without browser detect)?


You can check using the in operator:

"onpropertychange" in input

This kind of feature test doesn't work in older versions of Firefox, which report false event for event handler properties corresponding to events that do exist, but that isn't a problem here because Firefox doesn't currently support the propertychange event and is unlikely to in the future.

Here's some background: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/

One other point: you need separate functions to handle the propertychange and input events, because in the propertychange handler you need to check whether it is the value property that has changed. Otherwise, you'll end up handling changes to any property of the input.

input.onpropertychange = function(evt) {
    evt = evt || window.event;
    if (evt.propertyName == "value") {
        // Do stuff here
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜