我尝试过“window.getComputedStyle”和“currentStyle”,但除了chrome之外它不起作用。 请先看下面的演示,谢谢。 http://www.learning.fancyboy.net/javascript/cloneStyles.html 代码是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>clone style</title>
<style>
*{margin:0;padding:0;}
#text1{width:200px;height:50px;border:1px solid red;color:#ccc;line-height:50px;padding:5px;margin:5px;}
</style>
</head>
<body>
<div>
<input type="text" id="text1" value="origin" />
<input type="text" id="text2" value="clone" />
</div>
<script>
var
text1=document.getElementById("text1"),
text2=document.getElementById("text2"),
cssObj,
sCssText="";
if(!!window.getComputedStyle){
cssObj=window.getComputedStyle(text1,null);
sCssText=cssObj.cssText;
}
else{
cssObj=text1.currentStyle;
for(var k in cssObj){
sCssText+=k+":"+cssObj[k]+";";
}
}
text2.style.cssText=sCssText;
</script>
</body>
</html>
有什么想法吗?
答案 0 :(得分:2)
如果可能,我会尝试这样做:
<style>
*{margin:0;padding:0;}
.textclass{width:200px;height:50px;border:1px solid red;color:#ccc;line-height:50px;padding:5px;margin:5px;}
</style>
<input type="text" id="text1" value="origin" class="textclass" />
<input type="text" id="text2" value="clone" class="textclass" />
如果那不可能,那么你可以使用这个jQuery函数(来自http://upshots.org/javascript/jquery-copy-style-copycss):
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
if(style = dom.style){
for(var prop in style){
if(typeof style[prop] != 'function'){
returns[prop] = style[prop];
};
};
return returns;
};
return returns;
}
要复制的帮助器(@source的所有样式都传递给调用者):
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
// usage...
// $('#my-element').copyCSS('#another-element');
// or...
// $('#my-element').copyCSS(someReferenceToAnElement);
答案 1 :(得分:0)
.cssTExt,请参阅此http://www.javascriptkit.com/dhtmltutors/externalcss2.shtml