簡體   English   中英

CSS屬性的跨瀏覽器動態設置

[英]Cross-browser dynamic setting of a CSS property

我有一個函數可以獲取許多數據並為已定義的元素設置CSS屬性。

這是代碼:

function setStyle(element,property,target){
     element.style[property] = target;
}

var EL = document.getElementById("id");
setStyle(EL,"width","50px");

它適用於大多數瀏覽器,但不適用於IE6-IE9。

我找到了document.defaultView.getComputedStyleelement.currentStyle[type] ,但是這些方法得到了樣式,我無法使用它們進行設置。

有沒有辦法為舊IE做到這一點?

我不想使用jQuery或任何其他JS庫 ,謝謝。

默認方式是element.style.property = "value" ,如:

document.getElementById("id").style.width = "50px";

它沒有理由不起作用。 但是,作為替代方案,請考慮在類中設置css樣式,並通過className屬性將其添加到元素中。它受到廣泛支持:

CSS:

.myClass { width: 50px; }

JS:

document.getElementById("id").className = "myClass";



編輯

另一種方式,在IE8 +中工作(如果你真的不需要更低的東西)將設置DOM元素的實際style屬性,所以你可以將屬性作為參數:

http://jsfiddle.net/ppf5qcvo/

function setStyle(element,property,target){
    element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");

你考慮過使用jQuery嗎? 它為您處理所有跨瀏覽器問題。 您可以使用以下語句完成相同的操作:

$('#id').width('50px');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM