新的CSSStyleDeclaration [英] new CSSStyleDeclaration

查看:32
本文介绍了新的CSSStyleDeclaration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用浏览器的内置类型 CSSStyleDeclaration 来以编程方式传递和修改样式(由于具有 .cssText 属性,因此非常方便).

I'm trying to use the browser's built in type CSSStyleDeclaration to programatically pass around and modify styles (which is handy because of the .cssText property).

但是,新的CSSStyleDeclaration()会引发非法构造函数错误.因此,我尝试了 Object.create(CSSStyleDeclaration.prototype),该方法似乎可以正常工作,但是生成的对象无法正常工作.例如,以这种方式创建的 CSSStyleDeclaration 上调用 .cssText 会引发非法调用.

However, new CSSStyleDeclaration() throws an Illegal Constructor error. So I tried Object.create(CSSStyleDeclaration.prototype), which appears to work, but the resulting object doesn't behave normally. For example, calling .cssText on a CSSStyleDeclaration created this way throws an Illegal invocation.

是否有一种正确"的方式来构造 CSSStyleDeclaration ?还是有更好的方法来使用内置类型以编程方式创建样式?

Is there a "right" way to construct CSSStyleDeclaration? Or is there a better way to create styles programmatically using the built-in types?

(我不想进行字符串操作,而宁愿避免创建自己的类型或添加第三者依赖性.)

(I don't want to do string manipulation and I'd rather avoid making my own types or adding a 3rd party dependency.)

推荐答案

您可以创建一个临时DOM元素并使用其 style 属性:

you may create a temporary DOM element and use its style property:

const rules = document.createElement('span').style;
rules.backgroundColor = 'red';
rules.cursor = 'pointer';
rules.color = 'white';

document.getElementById('style_string').innerHTML = rules.cssText;
document.getElementById('obj').style = rules.cssText;

<pre id="style_string"></pre>
<div id="obj">TEST</div>

这篇关于新的CSSStyleDeclaration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆