Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

css - jQuery check if element has a specific style property defined inline

I need to check whether an element has a defined css property given to it, but I'm having some trouble using the jQuery.css() function.

The property I'm looking for is width.

If the element does not have a defined width and I try this:

if(base.$element.css('width') !== 'undefined')

I get the browser's computed width.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a very simple (probably in much need of improvement) plugin I've thrown together that will get you the value of an inline style property (and return undefined if that property is not found):

?(function ($) {
    $.fn.inlineStyle = function (prop) {
         var styles = this.attr("style"),
             value;
         styles && styles.split(";").forEach(function (e) {
             var style = e.split(":");
             if ($.trim(style[0]) === prop) {
                 value = style[1];           
             }                    
         });   
         return value;
    };
}(jQuery));

You can call it like this:

//Returns value of "width" property or `undefined`
var width = $("#someElem").inlineStyle("width");

Here's a working example.

Note that it will only return the value for the first element in the matched set.

Since it returns undefined when that style property is not found, you can use it in your situation like this:

if (base.$element.inlineStyle("width")) {
    // It has a `width` property!
}

Update

Here's a much, much shorter version. I realised that prop("style") returns an object, not a string, and the properties of that object correspond to the available style properties. So you can just do this:

(function ($) {
    $.fn.inlineStyle = function (prop) {
        return this.prop("style")[$.camelCase(prop)];
    };
}(jQuery));

You may want to replace the use of $.camelCase with a custom camelcase function, since the jQuery one appears to be undocumented and is probably not good to rely upon. I just used it here as it's shorter.

Here's a working example of that one. Note that in this case, the return value will be the empty string if the style was not found on the element. That will still evaluate to false, so the above if statement should still work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...