最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - DOM replace entire style attribute (CSSStyleDeclaration) on element - Stack Overflow

programmeradmin8浏览0评论

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

myDOMElement.style.height = '400px';

But what if I want to pletely 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 puted style
var putedStyle = window.getComputedStyle(myDOMElement);

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

//Apply the entirety of putedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = putedStyle;

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

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

myDOMElement.style.height = '400px';

But what if I want to pletely 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 puted style
var putedStyle = window.getComputedStyle(myDOMElement);

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

//Apply the entirety of putedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = putedStyle;

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

Share Improve this question asked Jan 9, 2014 at 3:29 AlexZAlexZ 12.1k3 gold badges29 silver badges43 bronze badges 3
  • 2 Unfortunately, the style property is read-only. I'd look at a way to merge the putedStyle in – Phil Commented Jan 9, 2014 at 3:37
  • 3 why not use css class? just add the class to the specified element. – Freedom Commented Jan 9, 2014 at 3:37
  • This might help you stackoverflow./questions/3968593/… – skos Commented Jan 9, 2014 at 3:56
Add a ment  | 

1 Answer 1

Reset to default 6

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

发布评论

评论列表(0)

  1. 暂无评论