Inherit/Extend CSS properties onto another element

What's the most efficient way in jQuery to extend/inherit CSS properties from one element to another?

Desired effect

$('#blah').extendCSSTo('#me') // Is there a plugin or a good way to do this?
$('#me').css({ background: 'blue' });

#me will now have all the CSS of #blah and also background

CSS:

#blah {
    padding: 5px;
    width: 200px;
    height: 20px;
    border: 1px solid #333;
    font-family: "Verdana";
}

#me {
    position: absolute;
    left: 5px;
    top: 5px;
}

<div id="blah"></div>
<div id="me">test</div>

Edit: This will be used in a plugin so using classes and simply doing .addClass is not an option

I'm looking for the same effect as setting default value for plugin options, but instead for CSS:

$.extend([css object], [#blah css object], [#me css object])

$('#me').addClass('class');

这工作,不知道你是否可以使用相对于ID的CSS。


Try this.

function CloneStyle(sourceID, targetID){
    var myStyle;
    var source = document.getElementById(sourceID);
    var target = document.getElementById(targetID);
    if (window.getComputedStyle) {
        myStyle = window.getComputedStyle(source).cssText;
    }
    else if (source.currentStyle) {
        myStyle = $.extend(true, {}, source.currentStyle);
    } else {
        throw "antique browser!";
    }
    target.style.cssText = myStyle;
}

Now call like.

CloneStyle("blah", "me");
$('#me').css({ background: 'blue' });

Fiddle here: http://jsfiddle.net/naveen/3FdDp/


If you were to use CSS classes rather than ID references you could do the following:

$("#me").addClass($("#blah").attr("class"));

Which would copy the classes from #blah to #me

链接地址: http://www.djcxy.com/p/7586.html

上一篇: 微软表示IE9有并行JavaScript呈现和执行

下一篇: 将CSS属性继承/扩展到其他元素