如何在一个元素的typescript中设置多个CSS样式属性?

Sri*_*jan 10 css typescript tslint

请考虑以下代码段.我需要在typescript中设置多个CSS属性.为此,我尝试了以下代码.

public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
        if (attrs !== undefined) {
            Object.keys(attrs).forEach((key: string) => {
                element.style[key] = attrs[key];
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

对于上面的代码,我需要传递参数为

let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {font-size:'12px', color : 'red' , margin-top: '5px'});
Run Code Online (Sandbox Code Playgroud)

但是上面的代码抛出错误(tslint),因为Element隐式具有'any'类型,因为索引表达式不是'number'类型.(属性)HTMLElement.style:CSSStyleDeclaration.

请帮我 !!!

the*_*ide 26

尝试使用setAttribute.TypeScript没有该style属性Element.

element.setAttribute("style", "color:red; border: 1px solid blue;");
Run Code Online (Sandbox Code Playgroud)

此GitHub问题中的一些相关讨论:https: //github.com/Microsoft/TypeScript/issues/3263

  • 这应该完全被标记为已接受的答案,感谢@theUtherSide:D的帮助 (3认同)
  • 这段代码有副作用,它会杀死所有旧样式的定义。 (3认同)

ozO*_*Oli 6

我希望这可以帮助您或其他人...

您可以使用 aHTLMDivElement和其中CSSStyleDeclaration包含的来实现这一点。例如。

var container: HTMLDivElement;

container.style.color = "red";
container.style.fontSize = "12px";
container.style.marginTop = "5px";
Run Code Online (Sandbox Code Playgroud)

这也适用于继承自HTMLElement并具有style属性的其他类(例如HTMLBodyElement.


Hol*_*min 6

您正在搜索的 API 是:https : //developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
    if (attrs !== undefined) {
        Object.keys(attrs).forEach((key: string) => {
            element.style.setProperty(key, attrs[key]);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

对象键中不允许使用连字符,因此也请在此处使用 ':

let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。TypeScript 的 CSSStyleDeclaration 具有基于数字的索引(在此处其他答案的评论中引用),因此字符串键不起作用。setProperty 接受字符串键,并且与“style[key] = val”具有相同的效果,而无需诉诸不安全的类型。谢谢@HolgerJeromin (2认同)

edd*_*dia 5

派对晚了一点,但是无论如何...

实际的问题不是上style没有定义Element。这个词Element在开始时Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration只是一个句子的第一个字,因此大写。意味着它与Element对象没有任何关系-这很令人困惑。

但是,错误消息表示您正尝试使用下标运算符访问[]索引类型错误的属性。在您的情况下,您key的类型是,string但是它HTMLElement.style是一个CSSStyleDeclaration具有的索引签名的对象,[index: number]: string因此要求您的密钥是type number

索引签名来自typescript/lib/lib.dom.d.tsTypeScript安装中的声明文件。在那里你会发现CSSStyleDeclaration

因此,您可以做的只是简单地any像这样:

(<any>element.style)[key] = attr[key];
Run Code Online (Sandbox Code Playgroud)

这不是最好的解决方案,但它有效且简单。它还不需要您像使用时那样将样式化element.setAttribute

  • 它反映了浏览器。尝试:`myElement.style[0]`来访问myElement的第一个样式。 (3认同)
  • 顺便说一句:有谁知道为什么 TypeScript 声明文件中的 CSSStyleDeclaration 具有基于数字的索引签名而不是基于字符串的索引签名?对我来说毫无意义。 (2认同)