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

新手上路,请多包涵

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

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

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

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

请帮我 !!!

原文由 Srinivasan Natarajan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

尝试使用 setAttribute 。 TypeScript 在 — 上没有 Element style 属性。

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

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

原文由 theUtherSide 发布,翻译遵循 CC BY-SA 3.0 许可协议

派对有点晚了,但无论如何……

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

但是,错误消息意味着您正在尝试使用下标运算符 [] 访问属性,索引类型不正确。 In your case your key is of type string but HTMLElement.style is a CSSStyleDeclaration object which has an index signature of [index: number]: string 因此要求您的密钥类型为 number

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

所以你可以做的就是简单地转换为 any 就像这样:

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

这不是最好的解决方案,但它有效且简单。它也不需要像使用 element.setAttribute 时那样对样式进行字符串化。

原文由 eddipedia 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题