How to check if naturalWidth is supported?

2019-06-25 09:12发布

问题:

I have the following jQuery and wanted to test if naturalWidth is supported:

function special(image) {
    if (typeof this.naturalWidth != 'undefined') {
        //do something
    }
}

But this doesn't seem to work ? Any ideas ?

回答1:

Try this

function special(image) {
    if (image && image.naturalWidth) {
        //do something
    }
}


回答2:

Why not just include a naturalWidth / naturalHeight polyfill? https://gist.github.com/2209957

Given that, you can write code like alert($(img).naturalWidth()) where you'd otherwise have used alert(img.naturalWidth) and it should now work in all browsers, whether they support it natively or not.