$(document).ready(function(){
function checker() {
if ($(".check-box-label").css("background-color") === "none"){
$(".check-box-label").css("background-color", "#1F7566")
}else{
$(".check-box-label").css("background-color", "none")
}
};
});
$(".check-box-label").on("click", checker);
使用此代码,.check-box-label背景颜色会根据实际的背景颜色值设置为在单击时变为其他颜色,为什么它不起作用?谢谢
答案 0 :(得分:1)
几个问题
1。).css("backgroundColor")
返回rgb而不是十六进制,因此我添加了一种用于转换为十六进制的通用方法
2。)将background-color设置为none,将不起作用。您需要使用“透明”或“初始”代替
function rgb2hex(rgb) {
if ( rgb.search("rgb") == -1 ) {
return rgb;
} else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
function checker() {
var targetColor = "#1f7566";
var color = $(".check-box-label").css("backgroundColor");
console.log(rgb2hex(color), rgb2hex(color) != targetColor)
if (rgb2hex(color) != targetColor){
$(".check-box-label").css("background-color", targetColor)
}else{
$(".check-box-label").css("background-color", "initial")
}
};
$(".check-box-label").on("click", checker);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="check-box-label">
things
</label>
答案 1 :(得分:0)
您正在Jquery DOM内创建函数,您必须在DOM之外创建函数, 然后您可以在DOM中调用函数 选中此
function checker() {
if ($(".check-box-label").css("background-color") === "none"){
$(".check-box-label").css("background-color", "#1F7566")
}else{
$(".check-box-label").css("background-color", "#1F7566")
}
};
$(function(){
$(".check-box-label").on("click", checker);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="check-box-label">
click me
</div>