How can I set multiple CSS styles in JavaScript?

2019-01-03 07:48发布

I have the following JavaScript variables:

var fontsize = "12px"
var left= "200px"
var top= "100px"

I know that I can set them to my element iteratively like this:

document.getElementById("myElement").style.top=top
document.getElementById("myElement").style.left=left

Is it possible to set them all together at once, something like this?

document.getElementById("myElement").style = allMyStyle 

15条回答
等我变得足够好
2楼-- · 2019-01-03 08:28

Make a function to take care of it, and pass it parameters with the styles you want changed..

function setStyle( objId, propertyObject )
{
 var elem = document.getElementById(objId);
 for (var property in propertyObject)
    elem.style[property] = propertyObject[property];
}

and call it like this

setStyle('myElement', {'fontsize':'12px', 'left':'200px'});

for the values of the properties inside the propertyObject you can use variables..

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-03 08:32

You can have individual classes in your css files and then assign the classname to your element

or you can loop through properties of styles as -

var css = { "font-size": "12px", "left": "200px", "top": "100px" };

for(var prop in css) {
  document.getElementById("myId").style[prop] = css[prop];
}
查看更多
我只想做你的唯一
4楼-- · 2019-01-03 08:32

Using plain Javascript, you can't set all the styles at once; you need to use single lines for each of them.

However, you don't have to repeat the document.getElementById(...).style. code over and over; create an object variable to reference it, and you'll make your code much more readable:

var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;

...etc. Much easier to read than your example (and frankly, just as easy to read as the jQuery alternative).

(if Javascript had been designed properly, you could also have used the with keyword, but that's best left alone, as it can cause some nasty namespace issues)

查看更多
登录 后发表回答