jquery - 我无法使用此代码在单击时更改类背景颜色。为什么?
问题描述
$(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 背景颜色应该在点击时根据实际背景颜色值交替颜色,为什么它不起作用?谢谢
解决方案
几个问题,
1.).css("backgroundColor")
返回 rgb,而不是 hex,所以我添加了一个常用的方法,用于转换为 hex
2.) 将背景颜色设置为无,将不起作用。您需要改用“透明”或“初始”
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>
推荐阅读
- spring - 在春季卡夫卡中面临“AddOffsetsToTxnResponse 中的意外错误”问题
- python - Databricks - 在 python 控制台中运行创建替换视图
- python - Python 测试入门
- c# - XAML 热重载不适用于自定义生成配置
- javascript - 如何在没有收集的情况下在 Firestore 内创建 Auto-ID?
- react-native - 如何解决 React Native IOS 中弃用的 API 使用 WebViewi?
- python - 数据库创建失败 - Flask - Postgres
- python - 如何在 python exe 文件中传递参数?
- liferay - Liferay7:@Reference(target = "(component.name=String.Here)") 我如何设置 String.Here?
- apache-spark - 使用 Apache Spark 写入具有有限权限的 S3 存储桶