我尝试使用 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>
最佳答案
使用 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;
}
在我的代码中,我覆盖了 bootstrap 的 css
代码。现在它可以正常工作了
关于jquery按钮颜色开关不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43418461/