使用 Javascript/jQuery 从外部样式表获取 CSS 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2707790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a CSS value from external style sheet with Javascript/jQuery
提问by Acorn
Is it possible to get a value from the external CSS of a page if the element that the style refers to has not been generated yet? (the element is to be generated dynamically).
如果样式所引用的元素尚未生成,是否可以从页面的外部 CSS 中获取值?(元素是动态生成的)。
The jQuery method I've seen is $('element').css('property');, but this relies on elementbeing on the page. Is there a way of finding out what the property is set to within the CSS rather than the computed style of an element?
我见过的 jQuery 方法是$('element').css('property');,但这依赖于element在页面上。有没有办法找出在 CSS 中设置的属性而不是元素的计算样式?
Will I have to do something ugly like add a hidden copy of the element to my page so that I can access its style attributes?
我是否必须做一些丑陋的事情,例如将元素的隐藏副本添加到我的页面,以便我可以访问其样式属性?
采纳答案by karim79
With jQuery:
使用 jQuery:
// Scoping function just to avoid creating a global
(function() {
var $p = $("<p></p>").hide().appendTo("body");
console.log($p.css("color"));
$p.remove();
})();
p {color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using the DOM directly:
直接使用DOM:
// Scoping function just to avoid creating a global
(function() {
var p = document.createElement('p');
document.body.appendChild(p);
console.log(getComputedStyle(p).color);
document.body.removeChild(p);
})();
p {color: blue}
Note:In both cases, if you're loading external style sheets, you'll want to wait for them to load in order to see their effect on the element. Neither jQuery's readynor the DOM's DOMContentLoadedevent does that, you'd have to ensure it by watching for them to load.
注意:在这两种情况下,如果您正在加载外部样式表,您需要等待它们加载以查看它们对元素的影响。jQueryready和 DOM 的DOMContentLoaded事件都不会这样做,您必须通过观察它们加载来确保它。
回答by Old Pro
Normally you should be let the browser apply all the rules and then ask the browser for the results, but for the rare case where you really need to get the value out of the style sheet you can use this: (JSFiddle)
通常,您应该让浏览器应用所有规则,然后向浏览器询问结果,但在极少数情况下,您确实需要从样式表中获取值,您可以使用:(JSFiddle)
function getStyleSheetPropertyValue(selectorText, propertyName) {
// search backwards because the last match is more likely the right one
for (var s= document.styleSheets.length - 1; s >= 0; s--) {
var cssRules = document.styleSheets[s].cssRules ||
document.styleSheets[s].rules || []; // IE support
for (var c=0; c < cssRules.length; c++) {
if (cssRules[c].selectorText === selectorText)
return cssRules[c].style[propertyName];
}
}
return null;
}
alert(getStyleSheetPropertyValue("p", "color"));
Note that this is pretty fragile, as you have to supply the full selector text that matches the rule you are looking up (it is not parsed) and it does not handle duplicate entries or any kind of precedence rules. It's hard for me to think of a case when using this would be a good idea, but here it is just as an example.
请注意,这非常脆弱,因为您必须提供与您正在查找的规则匹配的完整选择器文本(未解析),并且它不处理重复条目或任何类型的优先规则。我很难想到使用它是个好主意的案例,但这里只是一个例子。
回答by David Hobs
In response to Karim79, I just thought I'd toss out my function version of that answer. I've had to do it several times so this is what I wrote:
在回应 Karim79 时,我只是想我会扔掉那个答案的函数版本。我不得不这样做几次,所以这就是我写的:
function getClassStyles(parentElem, selector, style){
elemstr = '<div '+ selector +'></div>';
var $elem = $(elemstr).hide().appendTo(parentElem);
val = $elem.css(style);
$elem.remove();
return val;
}
val = getClassStyles('.container:first', 'class="title"', 'margin-top');
console.warn(val);
This example assumes you have and element with class="container" and you're looking for the margin-top style of the title class in that element. Of course change up to fit your needs.
这个例子假设你有一个带有 class="container" 的元素,并且你正在寻找那个元素中标题类的边距顶部样式。当然可以根据自己的需要进行调整。
In the stylesheet:
在样式表中:
.container .title{ margin-top:num; }
Let me know what you think - Would you modify it, and if so how? Thanks!
让我知道您的想法 - 您会修改它吗,如果是,如何修改?谢谢!
回答by Marc Derksen
I have written a helper function that accepts an object with the css attributes to be retrieved from the given css class and fills in the the actual css attribute values. Example is included.
我编写了一个辅助函数,它接受一个对象,该对象具有要从给定 css 类中检索的 css 属性,并填充实际的 css 属性值。包括示例。
function getStyleSheetValues(colScheme) {
var tags='';
var obj= colScheme;
// enumerate css classes from object
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
tags+= '<span class="'+prop+'"></span>';
}
}
// generate an object that uses the given classes
tags= $('<div>'+tags+'</div>').hide().appendTo("body");
// read the class properties from the generated object
var idx= 0;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
var nobj= obj[prop];
for (var nprop in nobj) {
if (nobj.hasOwnProperty(nprop) && typeof(nobj[nprop])=="string") {
nobj[nprop]= tags.find("span:eq("+idx+")").css(nobj[nprop]);
}
}
idx++;
}
}
tags.remove();
}
// build an object with css class names where each class name contains one
// or more properties with an arbitrary name and the css attribute name as its value.
// This value will be replaced by the actual css value for the respective class.
var colorScheme= { chart_wall: {wallColor:'background-color',wallGrid:'color'}, chart_line1: { color:'color'} };
$(document).ready(function() {
getStyleSheetValues(colorScheme);
// debug: write the property values to the console;
if (window.console) {
var obj= colorScheme;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
var nobj= obj[prop];
for (var nprop in nobj) {
if (nobj.hasOwnProperty(nprop)) {
console.log(prop+'.'+nprop +':'+ nobj[nprop]);
}
}
}
}
// example of how to read an individual css attribute value
console.log('css value for chart_wall.wallGrid: '+colorScheme.chart_wall.wallGrid);
}
});
回答by fenadoruk
I wrote this js function, seems to be working for nested classes as well:
我写了这个 js 函数,似乎也适用于嵌套类:
usage:
用法:
var style = get_css_property('.container-class .sub-container-class .child-class', 'margin');
console.log('style');
function get_css_property(class_name, property_name){
class_names = class_name.split(/\s+/);
var container = false;
var child_element = false;
for (var i = class_names.length - 1; i >= 0; i--) {
if(class_names[i].startsWith('.'))
class_names[i] = class_names[i].substring(1);
var new_element = $.parseHTML('<div class="' + class_names[i] + '"></div>');
if(!child_element)
child_element = new_element;
if(container)
$(new_element).append(container);
container = new_element;
}
$(container).hide().appendTo('body');
var style = $(child_element).css(property_name);
$(container).remove();
return style;
}

