简体   繁体   中英

Cross-browser dynamic setting of a CSS property

I have a function that gets many pieces of data and sets a CSS property for a defined element.

Here is the code:

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

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

It works well in most browsers but not for IE6–IE9.

I've found document.defaultView.getComputedStyle and element.currentStyle[type] , but these methods get style and I can't use them to set.

Is there any way to do that for old IEs?

i don't want to use jQuery or any other JS library , thanks.

The default way would be element.style.property = "value" , like:

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

There's no reason why it shouldn't work. But, as an alternative, consider setting the css style in a class, and adding it to the element by the className property.. It is widely supported:

css:

.myClass { width: 50px; }

js:

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



EDIT

Yet another way around, that works in IE8+ (If you don't really need anything lower) would be setting the actual style atribute to the DOM element, so you can get the property as a parameter:

http://jsfiddle.net/ppf5qcvo/

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

Have you considered using jQuery? It handles all the cross browser issues for you. You could accomplish the same thing with the following statement:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM