我正在尝试根据查询移动翻盖开关是打开还是关闭来更改 2 个类的文本颜色。我的印象是,翻转开关只是一个复选框,选中打开状态,取消选中关闭状态。我的 javascript 经验非常少。 任何人都知道我该如何解决这个问题?
类(class)
<div class="text-left">Make me blue when switch is off and grey when on </div>
<div class="text-right">Make me blue when switched is on and grey when off</div>
切换
<form>
<input type="checkbox" data-role="flipswitch" name="flip-checkbox-4" id="flip-checkbox-4" data-wrapper-class="custom-size-flipswitch">
</form>
JavaScript
<script type="text/javascript">
if($("#flip-checkbox-4").is(":checked")) {
$(".text-left").css("color", "grey");
$(".text-right").css("color", "blue");
} else {
$(".text-left").css("color", "blue");
$(".text-right").css("color", "grey")
}
</script>
最佳答案
您需要将它包装在一个事件中;具体来说,一个 change()
事件,用于监听输入的 checked
属性何时更改:
$("#flip-checkbox-4").change(function(){
if($("#flip-checkbox-4").is(":checked")) {
$(".text-left").css("color", "grey");
$(".text-right").css("color", "blue");
} else {
$(".text-left").css("color", "blue");
$(".text-right").css("color", "grey")
}
});
更简单的方法:
$("#flip-checkbox-4").change(function(){
$(".text-left").css("color", this.checked ? "grey" : "blue");
$(".text-right").css("color", this.checked ? "blue" : "grey");
});
关于javascript - 使用 jQuery 移动翻转开关更改文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21807356/