【问题标题】:DOM replace entire style attribute (CSSStyleDeclaration) on elementDOM 替换元素上的整个样式属性 (CSSStyleDeclaration)
【发布时间】:2014-01-27 11:12:30
【问题描述】:

我知道要替换单个样式,代码如下所示:

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;

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

【问题讨论】:

  • 不幸的是,style 属性是只读的。我会想办法将computedStyle 合并到
  • 为什么不用css类?只需将类添加到指定的元素。

标签: javascript css dom


【解决方案1】:

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

您可以直接附加到样式属性。

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

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

【讨论】:

  • 嘿 Jeremy,这是一个非常棒的解决方案,绝对比简单地单独替换属性要快!我做了一点速度测试,你的解决方案在我的浏览器上快了大约 3 倍(使用你的方法 100 倍大约是 200 毫秒,而使用另一种方法是 600 毫秒)。速度测试链接如下:codepen.io/azaslavsky/pen/ufHba
  • 很高兴为您提供帮助!我喜欢那个codepen界面,很干净。
  • 谢谢@jeremyjjbrown,这对我也有帮助,我能够缩短我的情况,但 .cssText 很有效:) this.style.cssText = "cursor: pointer";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2011-07-27
  • 1970-01-01
  • 2016-10-02
  • 2021-08-28
相关资源
最近更新 更多