如何在一个元素的打字稿中设置多个CSS样式属性? [英] how to set multiple CSS style properties in typescript for an element?

查看:284
本文介绍了如何在一个元素的打字稿中设置多个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

这篇关于如何在一个元素的打字稿中设置多个CSS样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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