【问题标题】:TypeScript set css style for HTMLCollectionOf<Element>, NodeCollection<Element>,google autocomplete formsTypeScript 为 HTMLCollectionOf<Element>、NodeCollection<Element>、google 自动完成表单设置 css 样式
【发布时间】:2018-06-14 02:03:59
【问题描述】:

如何为 HTMLCollectionOf 或 NodeCollection 设置 css 样式

 let items = document.querySelectorAll('.pac-item') as NodeListOf<HTMLElement>;

对于 HTMLElement 设置样式运行良好

【问题讨论】:

标签: javascript html css typescript


【解决方案1】:

谢谢各位! 我的失败...那是元素的集合...通过迭代解决了它

 var items:any = document.getElementsByClassName('pac-item');
        for (let i = 0; i < items.length; i++) {
            let element = items[i];
            element.style.background = '#2B2B2B';
            element.style.color = '#DEDEDE';
        }

【讨论】:

  • 这会为我生成一个 TypeScript 错误,即“样式”在“元素”类型上不存在。如果您只是忽略编译器错误,该代码就可以工作,但是如果您想让它消失,您需要使用document.getElementsByClassName('pac-item') as HTMLCollectionOf&lt;HTMLElement&gt;
【解决方案2】:

typescript 定义表明 HTMLCollectionOf 是 HTMLCollection 的扩展,您需要对其进行迭代以访问各个元素。

interface HTMLCollectionOf<T extends Element> extends HTMLCollection {
    item(index: number): T;
    namedItem(name: string): T;
    [index: number]: T;
}

我希望这会有所帮助。 :)

【讨论】:

    【解决方案3】:

    您正在使用HtmlCollectionOf,所以它是一个集合,一个集合有很多项目。因此items.style.background 不起作用,因为它属于HtmlElement

    换句话说,您必须遍历集合以应用于每个HtmlElement。或者你可以申请如下特定的,我认为这是你想要做的

    items[0].style.background = '#2B2B2B';

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多