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

前端之家收集整理的这篇文章主要介绍了javascript – DOM替换元素上的整个样式属性(CSSStyleDeclaration)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道要替换单个样式,代码看起来像这样:
myDOMElement.style.height = '400px';

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

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

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

解决方法

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

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

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

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

原文链接:https://www.f2er.com/js/156773.html

猜你在找的JavaScript相关文章