admin管理员组文章数量:1328610
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 theputedStyle
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
1 Answer
Reset to default 6You 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".
本文标签: javascriptDOM replace entire style attribute (CSSStyleDeclaration) on elementStack Overflow
版权声明:本文标题:javascript - DOM replace entire style attribute (CSSStyleDeclaration) on element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742234219a2437774.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论