將style
屬性設置爲元素在IE 6/7中不起作用。但在其他瀏覽器中,它運行良好。setAttribute風格在IE中不起作用
我使用的代碼是
var box_style = 'width: 200px; background:red';
document.getElementById('box').setAttribute("style", box_style);
這適用於所有其他的瀏覽器IE除外6/7
難道我做錯了什麼?或者是否有解決這個問題的方法?請幫忙 !
將style
屬性設置爲元素在IE 6/7中不起作用。但在其他瀏覽器中,它運行良好。setAttribute風格在IE中不起作用
我使用的代碼是
var box_style = 'width: 200px; background:red';
document.getElementById('box').setAttribute("style", box_style);
這適用於所有其他的瀏覽器IE除外6/7
難道我做錯了什麼?或者是否有解決這個問題的方法?請幫忙 !
嘗試改變,要
var box = document.getElementById('box');
box.style.width = '200px';
box.style.backgroundColor = 'red';
Internet Explorer 6-7的setAttribute/getAttribute的實現失效。不要使用它們。
從本質上講,的setAttribute(IE瀏覽器)看起來是這樣的:
function (attribute, value) {
this[attribute] = value;
}
因此,如果沒有一個1:屬性名和屬性名之間的一對一關係,它打破。
單獨設置您的屬性,或者,這通常更好,請設置className並在外部樣式表中定義樣式。
1。除非每個元素真的是唯一的樣式,'className' + stylesheet通常是一個更乾淨的方法。 – bobince 2010-07-13 13:28:29
另外,您可以使用PrototypeJS框架(http://www.prototypejs.org),它可以讓你做到以下幾點:
$('box').setStyle({
width: '200px',
backgroundColor : 'red'
});
的最終的答案是cssText
:
el.style.cssText = 'width: 200px; background:red';
備註是
避免在任何地方設置/ getAttribute!
感謝galambalazs ....它救了我的生命時間 – 2013-02-27 13:26:36
這對我的作品。和跨瀏覽器(甚至IE6) – 2013-04-11 08:46:16
可以使用的setAttribute即也兼容IE-8和IE-7
var el = document.getElementById('id' + id);
el.setAttribute('fontWeight','bold');
el.setAttribute('color','red');
el.setAttribute('fontSize','150%');
el.setAttribute('bgColor','red');
用於向元件分配一個類的話,建議下列
el.className = "class-name";
如何設置'-webkit-border-radius'和其他css3屬性? – 2010-07-13 13:04:31
一般規則:刪除連字符並大寫以下字母:'background-color'變爲'backgroundColor','-webkit-border-radius'變成'WebkitBorderRadius'。 – RoToRa 2010-07-13 13:19:35
實際上'-webkit'在這裏是個例外。它應該是'WebkitBorderRadius',就像它是'MozBorderRadius',但實際上它是'webkitBorderRadius'。 – bobince 2010-07-13 13:24:16