Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - jQuery是否可以获取与元素关联的所有CSS样式?(Can jQuery get all CSS styles associated with an element?)

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?

(jQuery中是否有一种方法可以从现有元素中获取所有CSS并将其应用于另一个元素而不列出所有元素?)

I know it would work if they were a style attribute with attr() , but all of my styles are in an external style sheet.

(我知道如果它们是attr()的样式属性,它将起作用,但是我所有的样式都在外部样式表中。)

  ask by alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A couple years late, but here is a solution that retrieves both inline styling and external styling:

(迟了几年,但是这里有一个可以同时检索内联样式和外部样式的解决方案:)

function css(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css) {
    var s = {};
    if (!css) return s;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                s[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var l = css[i].split(": ");
            s[l[0].toLowerCase()] = (l[1]);
        }
    }
    return s;
}

Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css() , ex:

(将jQuery对象传递到css() ,它将返回一个对象,然后您可以将其插入jQuery的$().css() ,例如:)

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);

:)

(:))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...