DOM replace entire style attribute (CSSStyleDeclaration) on element

I know that to replace a single style, the code looks something like this:

myDOMElement.style.height = '400px';

But what if I want to completely replace the entire style object in one fell swoop, thereby speeding things up and avoiding redraws? For example, I would like to do this:

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

However, when I run this code, my new style just gets ignored. What can I do to fix this?


You really don't want to use getComputedStyle("myElement") because versions of IE doesn't support it.

You can just append to the style attribute directly.

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

myStyle can contain many css rules so you'll get them all in one redraw. As a bonus you get the added CSS Specificity Value of an inline style, which will override everything else but "!important".

链接地址: http://www.djcxy.com/p/76764.html

上一篇: 跨域请求不能在Safari中使用SoundCloud

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