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:06

set multiple css style properties in Javascript

document.getElementById("yourElement").style.cssText = cssString;

or

document.getElementById("yourElement").setAttribute("style",cssString);

Example:

document
.getElementById("demo")
.style
.cssText = "margin-left:100px;background-color:red";

document
.getElementById("demo")
.setAttribute("style","margin-left:100px; background-color:red");
查看更多
贼婆χ
3楼-- · 2019-01-03 08:06

See for .. in

Example:

var myStyle = {};
myStyle.fontsize = "12px";
myStyle.left= "200px";
myStyle.top= "100px";
var elem = document.getElementById("myElement");
var elemStyle = elem.style;
for(var prop in myStyle) {
  elemStyle[prop] = myStyle[prop];
}
查看更多
仙女界的扛把子
4楼-- · 2019-01-03 08:10

There are scenarios where using CSS alongside javascript might make more sense with such a problem. Take a look at the following code:

document.getElementById("myElement").classList.add("newStyle");
document.getElementById("myElement").classList.remove("newStyle");

This simply switches between CSS classes and solves so many problems related with overriding styles. It even makes your code more tidy.

查看更多
冷血范
5楼-- · 2019-01-03 08:16

@Mircea: It is very much easy to set the multiple styles for an element in a single statement. It doesn't effect the existing properties and avoids the complexity of going for loops or plugins.

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

BE CAREFUL: If, later on, you use this method to add or alter style properties, the previous properties set using 'setAttribute' will be erased.

查看更多
小情绪 Triste *
6楼-- · 2019-01-03 08:16

Don't think it is possible as such.

But you could create an object out of the style definitions and just loop through them.

var allMyStyle = {
  fontsize: '12px',
  left: '200px',
  top: '100px'
};

for (i in allMyStyle)
  document.getElementById("myElement").style[i] = allMyStyle[i];

To develop further, make a function for it:

function setStyles(element, styles) {
  for (i in styles)
    element.style[i] = styles[i];
}

setStyles(document.getElementById("myElement"), allMyStyle);
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-03 08:17

With Zam you would do it like this

zam.css({'font-size':'12px','left':'200px','top':'100px'}, '#myElement');
查看更多
登录 后发表回答