因此,我在努力複製應用於一個元素(class/id/tagName/attribute等)的所有樣式。 到目前爲止,我發現我可以複製元素的計算樣式, 只是一個問題... couldend應用它outher元素;/從一個元素到另一個元素設置JavaScript的計算風格
或diffrend方式複製所有的樣式。
(這是據我得到:/) http://jsfiddle.net/8KdJd/2/
//queriks mode + minor changes to retrive the computed style
function getCS(el)
{
if (el.currentStyle)
var y = el.currentStyle;
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null);
return y;
}
function setCS(el,cs)
{
if (el.currentStyle)
{
el.currentStyle = cs;
el.style = cs;
}
else if (window.getComputedStyle)
{el.style = cs
}
}
var myLink = document.getElementById('myLink');
var anotherLink = document.getElementById('anotherLink');
var CS_myLink = getCS(myLink);
setCS(anotherLink,CS_myLink);
是否有一個特定的原因,你需要複製這樣的風格?根據這個問題http://stackoverflow.com/questions/344162/set-html-elements-style-property-in-javascript你不能只是分配一個「風格對象」元素的「風格」屬性就像你已經在你的'setCS'函數中完成。這樣做更簡單的方法是將'#myLink'的CSS定義更改爲'.myLink'等類,然後使用Javascript將myLink類添加到第二個鏈接元素。 – jingtao
嗨thx的迴應, 是的有一個原因,即時通訊這樣做, 我的代碼將適用於已經建成的網站,而不是我的控制。 –
所以我得到了它WebKit的(鉻到目前爲止)用下面的代碼工作, 問題是,IE瀏覽器返回空字符串.cssText財產 http://jsfiddle.net/8KdJd/4/ 功能setCS(EL ,CS) { \t如果(el.currentStyle) { ** el.style.cssText = cs.cssText; **如果 } \t其他(window.getComputedStyle) { el.style.cssText = cs.cssText; } –