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: 5开发者_如何学JAVApx;
}
<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');
This works, not sure if you can use the css relative to an ID though.
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
精彩评论