简体   繁体   English

使用 Javascript/jQuery 从外部样式表获取 CSS 值

[英]Get a CSS value from external style sheet with Javascript/jQuery

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?如果样式所引用的元素尚未生成,是否可以从页面的外部 CSS 中获取值? (the element is to be generated dynamically). (元素是动态生成的)。

The jQuery method I've seen is $('element').css('property');我见过的 jQuery 方法是$('element').css('property'); , but this relies on element being on the page. ,但这依赖于页面上的element Is there a way of finding out what the property is set to within the CSS rather than the computed style of an 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?我是否必须做一些丑陋的事情,例如将元素的隐藏副本添加到我的页面,以便我可以访问其样式属性?

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 ready nor the DOM's DOMContentLoaded event does that, you'd have to ensure it by watching for them to load . jQuery 的ready和 DOM 的DOMContentLoaded事件都没有做到这一点,您必须通过观察它们加载来确保它。

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.我很难想到使用它是个好主意的案例,但这里只是一个例子。

In response to Karim79, I just thought I'd toss out my function version of that answer.在回应 Karim79 时,我只是想我会扔掉那个答案的函数版本。 I've had to do it several times so this is what I wrote:我不得不这样做几次,所以这就是我写的:

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.这个例子假设你有一个带有 class="container" 的元素,并且你正在寻找那个元素中标题类的边距顶部样式。 Of course change up to fit your needs.当然可以根据自己的需要进行调整。

In the stylesheet:在样式表中:

 .container .title{ margin-top:num; }

Let me know what you think - Would you modify it, and if so how?让我知道您的想法 - 您会修改它吗,如果是,如何修改? Thanks!谢谢!

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 actual css attribute values.我编写了一个辅助函数,它接受一个对象,该对象具有要从给定 css 类中检索的 css 属性,并填充实际的 css 属性值。 Example is included.包括示例。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM