【问题标题】:Apply hover over all list items, except one that is specified将鼠标悬停在所有列表项上,指定的除外
【发布时间】:2019-04-02 07:30:46
【问题描述】:

在 Angular 2+ 中,是否有任何方法可以按照 Angular 代码的规定停止在列表项上悬停 CSS 功能?

我在这里有一个stackblitz 来展示一个简单的例子。

我正在使用ngClass 功能将样式动态应用于当时选择的任何列表项,因为这会改变(任何时候只会选择一项)。

<ul>
  <li id="{{item.name}}" *ngFor="let item of list" [ngClass]="{disableThis: item.selected}">{{item.name}}</li>
</ul>

我已经研究了 CSS 应用程序的 :not() 功能,但是我找不到一种方法让它与数据插值一起工作。

即:

.myElement:hover:not({{listItem.name}}) {
  background: green;
  color: white;
} 

【问题讨论】:

  • 选择器应该是.myElement:not(.disableThis):hover {。假设myElement 类应用于所有li 元素。
  • @Tushar - 你在开玩笑吗?就这么简单!?
  • @physicsboy Tushar 是正确的,更新的 stackblitz 在这里stackblitz.com/edit/angular-qhtykw

标签: javascript css angular typescript


【解决方案1】:

app.component.ts

  items = {
    name: 'name',
    lang: ['php', 'javascript', 'angular']
  };

app.component.html

<ul>
 <li id="{{item.name}}" class="items" *ngFor="let item of items.lang">{{item}}</li>
</ul>

app.component.css 或 app.component.scss

// 1
.items:not(:first-of-type):hover {
  color: red;
}

// 2
.items:not(:last-of-type):hover {
  color: red;
}

// 3
.items:not(:first-child):hover {
  color: red;
}

// 4
.items:not(:last-child):hover {
  color: red;
}

// 5 by index of item
.items:not(:nth-child(2)):hover {
  color: red;
}

// 6 by index of item
.items:not(:nth-child(3)):hover {
  color: red;
}

按选择器 ID


app.component.ts

items = [
    {
      id: 'php',
      lang: 'php'
    },
    {
      id: 'angular',
      lang: 'angular'
    },
    {
      id: 'css',
      lang: 'css'
    }
  ];

app.component.html

<ul>
    <li id="{{ item.id }}" class="items" *ngFor="let item of items">{{item.lang}}</li>
</ul>

app.component.css 或 app.component.scss

.items:not(#angular):hover {
  color: red;
}

// Or
.items:not(#php):hover {
  color: red;
}

// Or
.items:not(#css):hover {
  color: red;
}

【讨论】:

    【解决方案2】:

    如果停止悬停取决于附加了 disableThis 类的特定元素,您只需像这样修改您的 css:

    .disableThis,
    .disableThis:hover {
      background: grey;
      color: white;
    }
    

    【讨论】:

      【解决方案3】:

      @Tushar 赢得了这一天的快速评论:

      选择器应该是 .myElement:not(.disableThis):hover {。假设 myElement 类应用于所有 li 元素。

      这对我有用,也适用于我从中提取代码的大型项目。

      【讨论】: