带有Bootstrap和Angular ngFor的活动按钮的不同颜色

时间:2018-11-06 19:14:48

标签: angular bootstrap-4

我有一个菜单,其中包含四个按钮,这些按钮在被激活时具有定义的颜色,但是该颜色用于所有四个,与rollOver相同。有没有一种方法可以为活动状态和翻转中的每个按钮定义颜色?

enter image description here

.html

<div class="d-flex justify-content-center">
    <ul class="nav nav-pills subNav">
      <li class="nav-item" *ngFor="let linea of lineas">
        <a class="nav-link rounded-circle p-3 m-2 m-lg-3" routerLink="{{linea.url}}" routerLinkActive="active" >
          <img class="iconProduct" src="{{ linea.image }}">
        </a>
        <p class="small text-center">{{ linea.titulo }}</p>
      </li>
    </ul>
  </div>

.ts

this.lineas = [
      { image: 'assets/images/icon1.svg', url:'url1', titulo: 'title1'},
      { image: 'assets/images/icon2.svg', url:'url2', titulo: 'title2' },
      { image: 'assets/images/icon3.svg', url:'url3', titulo: 'title3'},
      { image: 'assets/images/icon4.svg', url:'url4', titulo: 'title4' }
      ]

.scss

.subNav .nav-link {
  background-color: #d5d5d5;
}

2 个答案:

答案 0 :(得分:2)

activehover状态设置背景颜色的一种方法是每个按钮都不同,这是使用:nth-child CSS伪类:

.subNav > .nav-item:nth-child(1) > .nav-link:hover,
.subNav > .nav-item:nth-child(1) > .nav-link.active {
  background-color: orange;
}

.subNav > .nav-item:nth-child(2) > .nav-link:hover,
.subNav > .nav-item:nth-child(2) > .nav-link.active {
  background-color: green;
}

.subNav > .nav-item:nth-child(3) > .nav-link:hover,
.subNav > .nav-item:nth-child(3) > .nav-link.active {
  background-color: red;
}

.subNav > .nav-item:nth-child(4) > .nav-link:hover,
.subNav > .nav-item:nth-child(4) > .nav-link.active {
  background-color: blue;
}

有关演示,请参见this stackblitz


另一种方法是在数据结构中定义活动状态颜色:

this.lineas = [
  { image: 'assets/images/icon1.svg', url:'url1', titulo: 'title1', activeColor: 'lime' },
  { image: 'assets/images/icon2.svg', url:'url2', titulo: 'title2', activeColor: 'green' },
  { image: 'assets/images/icon3.svg', url:'url3', titulo: 'title3', activeColor: 'red' },
  { image: 'assets/images/icon4.svg', url:'url4', titulo: 'title4', activeColor: 'blue'}
];

,并在设置active类时将其应用于链接的背景样式:

<a #link [style.background-color]="isActive(link) ? linea.activeColor : null" ...>
isActive(link): boolean {
  return link.classList.contains("active");
}

有关演示,请参见this stackblitz。您会注意到,在这种情况下,我为hover状态设置了默认颜色:

.subNav > .nav-item > .nav-link:hover {
  background-color: #c0c0c0;
}

如果要在鼠标悬停在链接上时应用数据中定义的自定义背景色,则可能需要处理鼠标enterleave事件。

答案 1 :(得分:0)

routerLinkActive被分配了一个类别,该类别应该应用于active li。在这种情况下,active是类。

尝试将active也添加到scss:

.active .subNav .nav-link {
  background-color: #d5d5d5;
}