jQuery检查元素是否具有内联定义的特定样式属性 [英] jQuery check if element has a specific style property defined inline

查看:954
本文介绍了jQuery检查元素是否具有内联定义的特定样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个元素是否有一个定义的css属性,但我使用jQuery.css()函数有些麻烦。

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.

我要找的属性是width。

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.

推荐答案

在非常需要改进)插件我已经在一起,将获得一个内联样式属性的值(并返回 undefined 如果找不到该属性):



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));

您可以这样调用:

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

以下是工作示例

请注意,它只会返回匹配集中第一个元素的值。

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

由于在找不到该样式属性时返回 undefined ,因此您可以在这种情况下使用它:

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!
}






/ strong>


Update

这里有一个非常简短的版本。我意识到 prop(style)返回一个对象,而不是一个字符串,该对象的属性对应于可用的样式属性。所以你可以这样做:

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));

您可能想要替换 $。camelCase 一个自定义的camelcase函数,因为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.

这里是一个工作示例那一个。注意,在这种情况下,如果在元素上找不到样式,返回值将是空字符串。这仍然会评估为 false ,因此上述如果语句仍然可以工作。

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.

这篇关于jQuery检查元素是否具有内联定义的特定样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆