如何在 JavaScript 中设置多个 CSS 样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3968593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:55:00  来源:igfitidea点击:

How can I set multiple CSS styles in JavaScript?

javascriptcoding-style

提问by Mircea

I have the following JavaScript variables:

我有以下 JavaScript 变量:

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 

回答by Laimis

Using Object.assign:

使用Object.assign

Object.assign(yourelement.style,{fontsize:"12px",left:"200px",top:"100px"});

This also gives you ability to merge styles, instead of rewriting the CSS style.

这也使您能够合并样式,而不是重写 CSS 样式。

You can also make a shortcut function:

你也可以做一个快捷功能:

const setStylesOnElement = function(styles, element){
    Object.assign(element.style, styles);
}

回答by Felix Kling

If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make use of the cssTextproperty:

如果您将 CSS 值作为字符串,并且没有为元素设置其他 CSS(或者您不关心覆盖),请使用cssText属性

document.getElementById("myElement").style.cssText = "display: block; position: absolute";

This is good in a sense as it avoids repainting the element every time you change a property (you change them all "at once" somehow).

这在某种意义上很好,因为它避免了每次更改属性时重新绘制元素(以某种方式“一次”更改它们)。

On the other side, you would have to build the string first.

另一方面,您必须先构建字符串。

回答by SHANK

@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.

@Mircea:在单个语句中为元素设置多种样式非常容易。它不会影响现有属性并避免使用 for 循环或插件的复杂性。

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.

小心:如果稍后您使用此方法添加或更改样式属性,则之前使用“setAttribute”设置的属性将被删除。

回答by Gabriele Petrioli

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..

对于 propertyObject 中的属性值,您可以使用变量..

回答by Harmen

A JavaScript library allows you to do these things very easily

一个 JavaScript 库可以让你很容易地做这些事情

jQuery

jQuery

$('#myElement').css({
  font-size: '12px',
  left: '200px',
  top: '100px'
});


Object and a for-in-loop

对象和 for 循环

Or, a much more elegant method is a basic object & for-loop

或者,更优雅的方法是使用基本对象和 for 循环

var el = document.getElementById('#myElement'),
    css = {
      font-size: '12px',
      left: '200px',
      top: '100px'
    };  

for(i in css){
   el.style[i] = css[i];
}

回答by eyupgevenim

set multiple css style properties in Javascript

在 Javascript 中设置多个 css 样式属性

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");

回答by Thielicious

I just stumbled in here and I don't see why there is so much code required to achieve this.

我只是在这里偶然发现,我不明白为什么需要这么多代码来实现这一点。

Add your CSS code as a string.

将您的 CSS 代码添加为字符串。

let styles = `
    font-size:15em;
    color:red;
    transform:rotate(20deg)`

document.querySelector('*').style = styles
a

回答by Sachin Shanbhag

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

您可以在 css 文件中拥有单独的类,然后将类名分配给您的元素

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];
}

回答by Spudley

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

使用普通的 Javascript,你不能一次设置所有的样式;你需要为每一个使用单行。

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:

但是,您不必一遍document.getElementById(...).style.又一遍地重复代码;创建一个对象变量来引用它,你会让你的代码更具可读性:

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).

...等等。比你的例子更容易阅读(坦率地说,就像 jQuery 替代品一样容易阅读)。

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

(如果 Javascript 设计得当,您也可以使用with关键字,但最好不要管它,因为它会导致一些令人讨厌的命名空间问题)

回答by nnevala

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);