DOM替换元素上的整个样式属性(CSSStyleDeclaration)

Ale*_*exZ 7 javascript css dom

我知道要替换单个样式,代码看起来像这样:

myDOMElement.style.height = '400px';
Run Code Online (Sandbox Code Playgroud)

但是,如果我想一举完全替换整个样式对象,从而加快速度并避免重绘,该怎么办?例如,我想这样做:

//Get the computed style
var computedStyle = window.getComputedStyle(myDOMElement);

//Change some stuff in that CSSStyleDeclaration without rendering
computedStyle.height = '10px';
computedStyle.width = '20px';
computedStyle.whatever = 'something';

//Apply the entirety of computedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = computedStyle;
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此代码时,我的新样式才会被忽略.我该怎么做才能解决这个问题?

jer*_*own 5

你真的不想使用getComputedStyle("myElement"),因为IE的版本不支持它.

您可以直接附加到style属性.

var myStyle = "color: #090";
document.getElementById("myElement").style.cssText += '; ' + myStyle; // to append
document.getElementById("myElement").style.cssText = myStyle; // to replace
Run Code Online (Sandbox Code Playgroud)

myStyle可以包含许多css规则,因此您可以在一次重绘中获取它们.作为奖励,您可以获得内联样式的CSS特性值,它将覆盖"!important"之外的所有内容.