【问题标题】:How can I get list of all element css attributes with jQuery?如何使用 jQuery 获取所有元素 css 属性的列表?
【发布时间】:2010-12-01 01:31:50
【问题描述】:

我需要获取所有 css 属性的元素列表。我该怎么做?

【问题讨论】:

标签: jquery css


【解决方案1】:

对于内联样式:

var styles = $("#someelement").attr("style");

如果您需要循环样式,您应该可以从那里拆分此字符串。

要检查单个样式,请查看文档:

http://docs.jquery.com/CSS

【讨论】:

  • 我还需要在 css 中设置的属性
  • 也许可以解释您在问题中要完成的工作。您最好检查单个样式,或者使用类并使用 .hasClass() - gnarf 在下面有一个链接
【解决方案2】:

从 jQuery 1.8 开始,您可以这样做:

$( "#yourElement" ).css( "cssText" );

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

【讨论】:

  • @EJTH 我是 jQuery 中该代码的作者 ;-)
  • 谢谢!您帮助我解决了将东西移动到 dom 中的某个容器的问题,而不会丢失任何样式! :-) 我将它用于一些宠物项目,使用 box2d 制作 HTML 页面...
  • 哇!我喜欢这个!如果您想要转储现有的每个 CSS 属性,这简直是最好的方法!
【解决方案3】:

SO1004475 - jQuery CSS plugin that returns computed style of element to pseudo clone that element?复制源代码 - 如果您觉得有用,请点击链接并在那里投票。

这看起来很荒谬,但这可能是你最好的选择 - 让没有参数的.css() 得到一个包含所有这些东西的对象。

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

请注意,这并不能捕获所有可能的 CSS 属性,尤其是 CSS3 的新属性。这是list of all standard CSS and stable CSS3 properties,这是hyphen-prefixed vendor-specific properties 之一(例如-moz-border-start)。如果你真的想要所有这些,你可以从那里收集它们。

【讨论】:

  • 同意 - 但我认为这是 OP 所要求的。
  • 已编辑以避免使用 css2 函数污染 jQuery.fn 命名空间。否则,这是很棒的东西。
  • @gnarf 请注意,自 1.9 以来的 jQuery 可以在其 css 方法中采用一组属性,因此此处不需要循环。
  • 不错的脚本,我没有看到盒子阴影?
【解决方案4】:
$("#div1).css("background-color");

将返回 id 为 div1 的元素的背景颜色属性。

css( name )

抱歉,我不知道如何使用 jQuery 获取所有 CSS 属性。

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 2013-05-10
    • 1970-01-01
    • 2011-02-15
    • 2011-01-04
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多