TypeScript 为 HTMLCollectionOf<Element>、NodeCollection<Element>、google 自动完成表单设置 css 样式

问题描述 投票:0回答:3

如何为 HTMLCollectionOf 或 NodeCollection 设置 css 样式?

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

对于 HTMLElement 设置样式效果很好

javascript html css typescript
3个回答
5
投票

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

 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';
        }

3
投票

打字稿定义表明

HTMLCollectionOf
是 HTMLCollection 的扩展,您需要迭代它才能访问各个元素。

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

我希望这有帮助。 :)


1
投票

您正在使用

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

换句话说,您必须循环遍历集合才能应用于每个

HtmlElement
。或者您可以申请如下所示的特定项目,我认为这就是您想要做的

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

© www.soinside.com 2019 - 2024. All rights reserved.