jquery按钮颜色开关不工作

时间:2017-04-14 20:01:59

标签: jquery

我尝试使用addClass()removeClass()hasClass()方法。但这个小代码根本不起作用?

查看所有3个功能的文档。好像应该有用。

<!DOCTYPE html>
<html>
<head>
<title>Trials</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
    .liked
    {
        color:red;
    }
</style>
</head>
<body>
<br><br><br>
<button id="like1" class="btn likeBtns liked">5<span class="glyphicon glyphicon-heart"></span></button>

<script>
$('.likeBtns').on('click', function(){

    var x = $(this).attr('id');
    x = "#"+x;
    if($("#like1").hasClass("liked"))
    {
        console.log("has");
        $("#like1").removeClass("liked");
    }
    else
    {
        console.log("doesnt have");
        $("#like1").addClass("liked");
    }
});
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:4)

使用toggleClass(),如下所示: -

工作示例: -

$('.likeBtns').on('click', function(){
  $(this).toggleClass("liked");
});
.liked{
  color:red;
}

.liked:hover,
.liked:focus,
.liked.focus {
    color:red !important;
}
<html>
  <head>
    <title>Trials</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </head>
  <body>
    <br><br><br>
    <button id="like1" class="btn likeBtns">5<span class="glyphicon glyphicon-heart"></span></button>
  </body>
</html>

注意: - 当您单击按钮然后单击外部时,将显示效果。

这是因为您的bootstrap.css已经在按钮上施加了低于css: -

btn.focus, .btn:focus, .btn:hover {
    color: #333;
    text-decoration: none;
}

在我的代码中,我覆盖了css bootstrap代码。现在它将完全正常

答案 1 :(得分:1)

如果您需要完全更改按钮颜色,则需要知道 btn 类还包含:hover:focus伪类。这意味着您需要添加.liked:hover和.liked:focus。

摘录:

&#13;
&#13;
$('.likeBtns').on('click', function(){
    $(this).toggleClass('liked')
});
&#13;
.liked
{
    color:red;
}
.liked:hover,
.liked:focus,
.liked.focus {
    color:red !important;
}
&#13;
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<button id="like1" class="btn likeBtns liked">5<span class="glyphicon glyphicon-heart"></span></button>
&#13;
&#13;
&#13;