简体   繁体   English

使用jQuery移动翻转开关更改文本颜色

[英]Change text color with jQuery mobile flip switch

I'm trying to change the text colour of 2 classes depending on whether the query mobile flip switch is on or off. 我正在尝试根据查询移动翻转开关是打开还是关闭来更改2类的文本颜色。 I was under the impression the flip switch was just a checkbox with the on state being checked and off state being unchecked. 我给人的印象是,拨动开关只是一个复选框,处于选中状态,处于打开状态,处于未选中状态。 My javascript experience is very minimal. 我的JavaScript经验很少。 Anyone know how I can fix this? 有人知道我该如何解决吗?

CLASSES CLASSES

<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>

SWITCH 开关

<form>
<input type="checkbox" data-role="flipswitch" name="flip-checkbox-4" id="flip-checkbox-4" data-wrapper-class="custom-size-flipswitch">
</form>

JAVASCRIPT 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>

You need to wrap it inside of an event; 您需要将其包装在事件内; specifically, a change() event, to listen out for when the checked property of the input is changed: 具体来说,是一个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")
  }
});

jsFiddle here. jsFiddle在这里。

A shorter way to do this: 一种更简单的方法:

$("#flip-checkbox-4").change(function(){
   $(".text-left").css("color", this.checked ? "grey" : "blue");
   $(".text-right").css("color", this.checked ? "blue" : "grey");
});

jsFiddle here. jsFiddle在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM