jQuery – 如何使用元素的HTML获取所有样式/ css(在内部/外部文档中定义)

我知道$("#divId").html()会给我innerHtml。 我还需要它的样式(可以通过类的方式定义)内联style属性或单独的标记内的所有样式/类。

可能吗?

UPDATE
如果html与

cfwcvb

并且#testDiv的css类在#testDiv中定义怎么办?

更新2
很抱歉没有提前澄清这一点

如果这是我的HTML

 
Some innerText

样式在单独的样式表或头部样式中定义。

 #divId { clear: both; padding: 3px; border: 2px dotted #CCC; font-size: 107%; line-height: 130%; width: 660px; } .someClass { color: blue; } 

然后,当我尝试获取$("#divId").html()内部html或调用任何其他自定义函数时,我需要以下内容

  #divId { clear: both; padding: 3px; border: 2px dotted #CCC; font-size: 107%; line-height: 130%; width: 660px; } .someClass { color: blue; }  
Some innerText

更新3由kirilloid回答
我在Chrome Debugger工具的命令窗口中为此页面本身运行了以下代码,这就是我看到的TypeError: Cannot read property 'rules' of undefined

 function getElementChildrenAndStyles(selector) { var html = $(selector).get(0).outerHTML; selector = selector.split(",").map(function(subselector){ return subselector + "," + subselector + " *"; }).join(","); elts = $(selector); var rulesUsed = []; // main part: walking through all declared style rules // and checking, whether it is applied to some element sheets = document.styleSheets; for(var c = 0; c < sheets.length; c++) { var rules = sheets[i].rules || sheets[i].cssRules; for(var r = 0; r < rules.length; r++) { var selectorText = rules[r].selectorText; var matchedElts = $(selectorText); for (var i = 0; i < elts.length; i++) { if (matchedElts.index(elts[i]) != -1) { rulesUsed.push(CSSrule); break; } } } } var style = rulesUsed.map(function(cssRule){ if ($.browser.msie) { var cssText = cssRule.style.cssText.toLowerCase(); } else { var cssText = cssRule.cssText; } // some beautifying of css return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}"); // set indent for css here ^ }).join("\n"); return "\n" + style + "\n\n\n" + html; }; getElementChildrenAndStyles(".post-text:first"); 

outerHTML (不确定,你需要它 – 以防万一)

限制:使用CSSOM ,样式表应来自同一个来源。

 function getElementChildrenAndStyles(selector) { var html = $(selector).outerHTML(); selector = selector.split(",").map(function(subselector){ return subselector + "," + subselector + " *"; }).join(","); elts = $(selector); var rulesUsed = []; // main part: walking through all declared style rules // and checking, whether it is applied to some element sheets = document.styleSheets; for(var c = 0; c < sheets.length; c++) { var rules = sheets[c].rules || sheets[c].cssRules; for(var r = 0; r < rules.length; r++) { var selectorText = rules[r].selectorText; var matchedElts = $(selectorText); for (var i = 0; i < elts.length; i++) { if (matchedElts.index(elts[i]) != -1) { rulesUsed.push(rules[r]); break; } } } } var style = rulesUsed.map(function(cssRule){ if (cssRule.style) { var cssText = cssRule.style.cssText.toLowerCase(); } else { var cssText = cssRule.cssText; } // some beautifying of css return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}"); // set indent for css here ^ }).join("\n"); return "\n\n" + html; } 

用法:

 getElementChildrenAndStyles("#divId"); 

没有jQuery也没有IE支持,这就是我所能做的:

在此处输入图像描述

       Test   
Some innerText

您可以使用大多数浏览器中的window.getComputedStyle()和IE中元素的currentStyle属性来获取表示元素计算样式的样式对象。 但是,有几种浏览器差异,其中返回了快捷方式属性(如background ),颜色RGB值,长度甚至font-weight (请参阅此有用的测试页 )。 仔细测试。

 function computedStyle(el) { return el.currentStyle || window.getComputedStyle(el, null); } alert(computedStyle(document.body).color); 

你可以在脚本中使用这样的东西: –

   

和简单的HTML将是这样的

 
cfwcvb

如果你想保存一个元素的所有风格,我认为这会更复杂,因为你首先想到的是我的第一个ide是firebug css控制台。 这显示了所有元素的风格,我想到了怎么样? 所以我搜索了萤火虫的源代码,我发现了这个:

http://fbug.googlecode.com/svn/branches/firebug1.7/content/firebug/css.js

此代码仅适用于css部分。

 const styleGroups = { text: [ "font-family", "font-size", "font-weight", "font-style", "color", "text-transform", "text-decoration", "letter-spacing", "word-spacing", "line-height", "text-align", "vertical-align", "direction", "column-count", "column-gap", "column-width" ], background: [ "background-color", "background-image", "background-repeat", "background-position", "background-attachment", "opacity" ], box: [ "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", "-moz-border-top-radius", "-moz-border-right-radius", "-moz-border-bottom-radius", "-moz-border-left-radius", "outline-top-width", "outline-right-width", "outline-bottom-width", "outline-left-width", "outline-top-color", "outline-right-color", "outline-bottom-color", "outline-left-color", "outline-top-style", "outline-right-style", "outline-bottom-style", "outline-left-style" ], layout: [ "position", "display", "visibility", "z-index", "overflow-x", // http://www.w3.org/TR/2002/WD-css3-box-20021024/#overflow "overflow-y", "overflow-clip", "white-space", "clip", "float", "clear", "-moz-box-sizing" ], other: [ "cursor", "list-style-image", "list-style-position", "list-style-type", "marker-offset", "user-focus", "user-select", "user-modify", "user-input" ] }; 

获取所有样式的函数。

 updateComputedView: function(element) { var win = element.ownerDocument.defaultView; var style = win.getComputedStyle(element, ""); var groups = []; for (var groupName in styleGroups) { var title = $STR("StyleGroup-" + groupName); var group = {title: title, props: []}; groups.push(group); var props = styleGroups[groupName]; for (var i = 0; i < props.length; ++i) { var propName = props[i]; var propValue = stripUnits(rgbToHex(style.getPropertyValue(propName))); if (propValue) group.props.push({name: propName, value: propValue}); } } var result = this.template.computedTag.replace({groups: groups}, this.panelNode); dispatch(this.fbListeners, 'onCSSRulesAdded', [this, result]); } function stripUnits(value) { // remove units from '0px', '0em' etc. leave non-zero units in-tact. return value.replace(/(url\(.*?\)|[^0]\S*\s*)|0(%|em|ex|px|in|cm|mm|pt|pc)(\s|$)/gi, function(_, skip, remove, whitespace) { return skip || ('0' + whitespace); }); } 

在这段代码中我想通了

 win.getComputedStyle(element, "") 

获取元素的所有样式,然后使用for循环获取所有样式并打印出来。 所以我认为getComputedSTyle是要使用的主要function,在此之后你可以逐个获得道具:

 style.getPropertyValue(propName) 

基于kirilloid的答案,我为Chrome创建了一个开发人员工具扩展,其中包含用于捕获页面片段的样式和标记的代码。 该扩展程序位于Chrome网上应用店中 ,位于Github上 。 所有“作者样式”输出选项都使用该方法迭代样式表。

在此处输入图像描述

.css()方法获取元素的特定样式…我不知道您是否可以检索所有样式:

http://api.jquery.com/css/

通常,您可以使用.attr(’style’)访问样式参数。 如果要访问计算样式,可以在Opera,Firefox,Chrome和其他理想浏览器中使用window.getComputedStyle(element)。 对于IE,你会对element.currentStyle做同样的事情。

此外,如果您希望访问单独的CSS样式,您可以使用jQuery .css方法。 就像这样$(“#divId”)。css(’font-size’)。

您可以在document.styleSheets下的样式标记内定义样式表。 您可以将规则读入地图,然后通过selectorText查找它们。 所以通过id:“#id”,按类:“。className”。 通过safari或chrome,您可以使用getMatchedCSSRules 。