将样式对象应用于 DOM 元素

Jav*_*ter 1 javascript css

我知道我们可以.style像这样将 css 应用于 DOM 元素:

document.getElementById("test").style.color="red";

我想知道,是否可以应用样式对象,如下所示:

newStyle: {
  position : 'fixed';
  width : '300px';
  height : '20px';
  top : '0';
}
Run Code Online (Sandbox Code Playgroud)

如何newStyle通过使用申请.style,可以吗?(我们这里没有使用 jQuery)

Ori*_*iol 5

您可以使用Object.assign

Object.assign(myElement.style, {
  width: '300px',
  height: '20px'
});
Run Code Online (Sandbox Code Playgroud)

Object.assign(document.getElementById("test").style, {
  position: 'fixed',
  width: '300px',
  height: '100px',
  top: '0'
});
Run Code Online (Sandbox Code Playgroud)
<div id="test" style="background: green"></div>
Run Code Online (Sandbox Code Playgroud)