添加和删​​除活动 class

Add and remove active class

我有一个包含一些项目的导航栏。如何将活动 class 添加到单击的项目并从其他项目中删除? 我试图通过 document.getElementsByClassName 获取这些元素,但它抛出错误

既然你在谈论 LitElementwebcomponents most likely the component you are working on has a Shadow DOM.

因为查询文档从一开始就是一个错误,您希望查找发生在您的元素内部,而不是在顶级文档级别。

所以在你的一个组件中,获取具有特定 class 的所有元素而不是:

document.getElementsByClassName('item')

你会做类似的事情

this.shadowRoot.getElementsByClassName('item')

this.shadowRoot.querySelectorAll('.item')

您应该通过使用 classMap directive 绑定 class 属性 来完成此操作。根据文档 classMap:

Sets a list of classes based on an object. Each key in the object is treated as a class name, and if the value associated with the key is truthy, that class is added to the element.

例如,假设您的元素有一个 navItems 属性,如下所示:

this.navItems = [
  { id: 'home', href: '/', title: 'Home' },
  { id: 'contact', href: '/contact', title: 'Contact Us' },
];

...和 ​​activeNavItemId 属性 对应于其中一个 id。你可以这样渲染它们:

import { classMap } from 'lit-html/directives/class-map';

// ...

render() {
  return html`
    <nav>
      <ul>
        ${this.navItems.map(item => html`
          <li class=${classMap({ active: this.activeNavItemId === item.id })}>
            <a href=${item.href}>${item.title}</a>
          </li>
        `)}
      </ul>
    </nav>
  `;
}