bootstrap 下拉菜单打开时如何切换按钮图标

How to toggle button icon when a bootstrap dropdown is open

我有一个 bootstrap 下拉列表,我想在打开下拉列表时更改按钮中显示的图标 (icon-deafult)(更改为 图标激活)。这是代码:

<div id="Menu" class="dropdown">
  <a class="btn btn-default" id="MyButton" data-toggle="dropdown" role="button">
    <i class="icon-default"></i>
  </a>
  <ul class="dropdown-menu" role="menu">
    <li>...</li>
    <li>...</li>
  </ul>
</div>

.icon-default {
  content: url("path/path/cool.svg");
  background-size: cover;
}
.icon-active {
  content: url("path/path/hot.svg");
  background-size: cover;
}

我尝试使用 .open > .icon-default {...},但没有成功。我做对了吗?有没有办法在不编写任何新脚本的情况下做到这一点。我可以使用现有的 CSS 或 bootstrap 功能来完成这项工作吗?

如果您的下拉列表在您打开时显示 class open,那么您应该更新您的选择器:

.open .icon-default {
  content: url("path/path/hot.svg");
}

Bootstrap 使用 area-expended 属性,因此您可以使用 [aria-expanded="false"] 关闭下拉菜单,使用 [aria-expanded="true"] 打开下拉菜单。

// When dropdown is closed
.dropdown > [aria-expanded="false"] > .icon-default {
    content: url("path/path/cool.svg");
}

// when dropdown is opened
.dropdown > [aria-expanded="true"] > .icon-default {
    content: url("path/path/hot.svg");
}

这对我有用

#navbarDropdownMenuLink[aria-expanded="true"]:after{
  content: url("path/path/hot.svg");
}

#navbarDropdownMenuLink[aria-expanded="false"]:after{
  content: url("path/path/cold.svg");
}