首页 > 解决方案 > Bootstrap 和 JavaScript 按钮更改具有背景颜色的图标

问题描述

我试图更改带有背景颜色的图标出现在点击事件上,但背景颜色没有改变。有什么解决方案吗?这是我的代码

jQuery(function($) {
  $('#swapFire').on('click', function() {
    var $el = $(this),
      textNode = this.lastChild;
    $el.find('span').toggleClass('glyphicon-fire glyphicon-tint');

    $el.toggleClass('showFire');
 
  });
});
.btn {
  margin: 20px;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>


<button id="swapFire" class="btn btn-primary showFire">
    <span class="glyphicon glyphicon-fire"></span> Gimme Fire
</button>

标签: javascripthtmlcsstwitter-bootstrap

解决方案


添加Toggle class

$el.toggleClass('btn-primary btn-danger');

jQuery(function($) {
  $('#swapFire').on('click', function() {
    var $el = $(this),
      textNode = this.lastChild;
    $el.find('span').toggleClass('glyphicon-fire glyphicon-tint');
    $el.toggleClass('btn-primary btn-danger');

    $el.toggleClass('showFire');
 
  });
});
.btn {
  margin: 20px;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>


<button id="swapFire" class="btn btn-primary showFire">
    <span class="glyphicon glyphicon-fire"></span> Gimme Fire
</button>


推荐阅读