如何在打字稿中为元素设置多个 CSS 样式属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37655393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:58:37  来源:igfitidea点击:

how to set multiple CSS style properties in typescript for an element?

csstypescripttslint

提问by Srinivasan Natarajan

Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.

请考虑以下片段。我需要在打字稿中设置多个 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];
            });
        }
    }

for the above code i need to pass the parameters as

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

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

But the above code throws error(tslint) as Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration.

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

Please help me !!!

请帮我 !!!

回答by theUtherSide

Try using setAttribute. TypeScript does not have the styleproperty on Element.

尝试使用setAttribute. TypeScript 没有style关于的属性Element

element.setAttribute("style", "color:red; border: 1px solid blue;");

Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263

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

回答by eddipedia

Just a little late to the party, but anyway...

聚会有点晚了,但无论如何......

The actual problem is not that styleis not defined on Element. The word Elementat the beginning of Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclarationis just the first word in a sentence and therefore uppercased. Means it does not relate in any way to the Elementobject - which is quite confusing.

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

However, the error message means that you are trying to access a property using the subscript operator []with an incorrectly typed index. In your case your keyis of type stringbut HTMLElement.styleis a CSSStyleDeclarationobject which has an index signature of [index: number]: stringand consequently requires your key to be of type number.

但是,该错误消息意味着您正在尝试使用下标运算符[]和错误键入的索引来访问属性。在您的情况下,您key是 type ,string但是HTMLElement.style是一个CSSStyleDeclaration具有索引签名的对象,[index: number]: string因此需要您的密钥为 type number

The index signature comes from the typescript/lib/lib.dom.d.tsdeclaration file in your TypeScript installation. There you will find CSSStyleDeclaration.

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

So what you can do is simply cast to anylike so:

所以你可以做的只是简单地转换为any喜欢这样:

(<any>element.style)[key] = attr[key];

It's not the best solution but it works and is straightforward. It also does not require you to stringify your styles like it would be necessary when you use element.setAttribute.

这不是最好的解决方案,但它有效并且很简单。它还不需要您像使用element.setAttribute.

回答by HolgerJeromin

The API you were searching for is: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

您正在搜索的 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]);
        });
    }
}

And hyphen is not allowed in object keys, so use ' here, too:

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

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

回答by ozOli

I hope this helps you or someone else...

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

You can achieve this using a HTLMDivElementand the CSSStyleDeclarationcontained within it. eg.

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

var container: HTMLDivElement;

container.style.color = "red";
container.style.fontSize = "12px";
container.style.marginTop = "5px";

This also applies to other classes that inherit from HTMLElementand have a styleproperty (for example HTMLBodyElement.

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