2016-02-04 52 views
1

我有一個div元素,並希望爲它添加新的樣式屬性。 我試圖做這樣的:用setAttribute()追加新屬性?

element.setAttribute('style', 'property: value'); 

和它的作品,但如果已經應用該元素的風格了,他們都將被覆蓋。

可以說我有這樣的情況:

HTML:

<div id="styled"></div> 

的JavaScript:

var styled = document.getElementById('styled'); 
styled.setAttribute('style', 'display: block'); 

這工作,但如果我需要追加另一種風格可以說:

styled.setAttribute('style', 'color: red'); 

然後我會失去在以前的setAttribute()方法中添加的樣式!

如何將樣式附加到JavaScript元素?

謝謝!

回答

3

好吧,如果使用setAttribute你可以只通過getAttribute取前值和Concat的他們:

element.setAttribute('style', element.getAttribute('style')+'; color: red'); 

但是,這不是最佳實踐f或大多數HTML屬性,這些屬性通常會作爲屬性反映出來,您可以僅執行一些操作,如element.className += " …"。特別是對於內嵌樣式,你會使用.style property,允許您設置和取消每一個CSS屬性:

element.style.display = 'block'; 
element.style.color = 'red'; 
+0

使用setAttribute改變風格是一個不好的破解。 – Kebman

0

當您使用setAttribute,您要更換整個style屬性,讓你失去任何樣式那已經在那裏了。你需要連接你的添加到舊的風格。

oldStyle = styled.getAttribute('style'); 
styled.setAttribute('style', oldStyle + 'color: red;'); 

但它的簡單使用style屬性的子屬性:

styled.style.color = 'red'; 
styled.style.display = 'block'; 

如果你需要從一個變量獲得樣式名稱,你可以使用數組符號:

styleName = 'color'; 
styleValue = 'red'; 
styled.style[styleName] = styleValue; 
1

如果您要添加的樣式,你可以將它們直接使用style屬性:

var foo = document.getElementById('foo'); 

foo.style.backgroundColor = 'red'; 
foo.style.width = '400px'; 
foo.style.height = '500px'; 
foo.style.fontWeight = 'bold';