如何在一个元素的打字稿中设置多个CSS样式属性?
请考虑以下代码段。我需要在打字稿中设置多个CSS属性。为此,我尝试了以下代码。
Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.
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'});
但是上面的代码抛出错误(tslint),因为Element隐式地具有 any类型,因为索引表达式不是数字类型。
(属性)HTMLElement.style:CSSStyleDeclaration。
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.
请帮助我!
尝试使用 setAttribute
。 TypeScript在 Element
上没有 style
属性。
Try using setAttribute
. TypeScript does not have the style
property on Element
.
element.setAttribute("style", "color:red; border: 1px solid blue;");
此GitHub问题中的一些相关讨论:
https://github.com/Microsoft/TypeScript/issues/3263
Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263