如何使用jQuery获取所有元素css属性的列表?

new*_*bie 13 css jquery

我需要得到所有css属性的元素列表.我怎样才能做到这一点 ?

gna*_*arf 20

SO1004475复制源- jQuery CSS插件返回计算的元素样式到伪克隆元素? - 如果您觉得有用,请关注链接和upvote.

这似乎很荒谬,但这可能是你最好的选择 - .css()没有参数的make会获得所有这些东西的对象.

jQuery.fn.css = (function(css2) { 
    return function() {
        if (arguments.length) { return css2.apply(this, arguments); }
        var attr = ['font-family','font-size','font-weight','font-style','color',
            'text-transform','text-decoration','letter-spacing','word-spacing',
            'line-height','text-align','vertical-align','direction','background-color',
            'background-image','background-repeat','background-position',
            'background-attachment','opacity','width','height','top','right','bottom',
            'left','margin-top','margin-right','margin-bottom','margin-left',
            'padding-top','padding-right','padding-bottom','padding-left',
            'border-top-width','border-right-width','border-bottom-width',
            'border-left-width','border-top-color','border-right-color',
            'border-bottom-color','border-left-color','border-top-style',
            'border-right-style','border-bottom-style','border-left-style','position',
            'display','visibility','z-index','overflow-x','overflow-y','white-space',
            'clip','float','clear','cursor','list-style-image','list-style-position',
            'list-style-type','marker-offset'];
        var len = attr.length, obj = {};
        for (var i = 0; i < len; i++) {
            obj[attr[i]] = css2.call(this, attr[i]);
        }
        return obj;
    };
})(jQuery.fn.css);
Run Code Online (Sandbox Code Playgroud)

请注意,这不会捕获所有可能的CSS属性,特别是CSS3的新属性.以下是所有标准CSS和稳定CSS3属性列表,这是一个以连字符为前缀的特定于供应商的属性(例如-moz-border-start).如果你真的想要所有这些,你可以从那里收集它们.

  • 编辑以避免使用`css2`函数污染`jQuery.fn`命名空间.否则,这是很棒的东西. (2认同)

Mik*_*rov 15

从jQuery 1.8开始,您可以:

$( "#yourElement" ).css( "cssText" );
Run Code Online (Sandbox Code Playgroud)

哪个使用底层window.getComputedStyle( element ).cssText.这是最简单的方法.

  • @EJTH我是jQuery中代码的作者;-) (2认同)