如何用javascript检测html开关状态

时间:2017-02-06 06:36:38

标签: javascript android-studio webview

我有一个HTML切换按钮(打开/关闭),我需要使用JavaScript检测它是打开还是关闭。请帮忙说明怎么做?

Here is my fiddle with the switch

2 个答案:

答案 0 :(得分:1)

为复选框元素添加'onchange'事件。请参阅下面的代码。

<div style="text-align: center;">
   <div class="switch">
      <input id="cmn-toggle-2" class="cmn-toggle cmn-toggle-round" type="checkbox" onchange="javascript:myFunction()">
      <label for="cmn-toggle-2"></label>
   </div>
</div>

<script>
    function myFunction() {
       alert(document.getElementById("cmn-toggle-2").checked);
    }
</script>

答案 1 :(得分:0)

试试这个

// checking wether the switch is on or off

var cb = document.getElementById("cmn-toggle-2");
cb.onchange = function() {
	if (cb.checked) alert('The Switch is ON!');
        else alert('The Switch is OFF!');
}
		.cmn-toggle {
		  position: absolute;
		  margin-left: -9999px;
		  visibility: hidden;
		}
		.cmn-toggle + label {
		  display: block;
		  position: relative;
		  cursor: pointer;
		  outline: none;
		  user-select: none;
		}

		input.cmn-toggle-round + label {
  padding: 2px;
  width: 120px;
  height: 60px;
  background-color: #dddddd;
  border-radius: 60px;
}
input.cmn-toggle-round + label:before,
input.cmn-toggle-round + label:after {
  display: block;
  position: absolute;
  top: 1px;
  left: 1px;
  bottom: 1px;
  content: "";
}
input.cmn-toggle-round + label:before {
  right: 1px;
  background-color: #f1f1f1;
  border-radius: 60px;
  transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
  width: 58px;
  background-color: #fff;
  border-radius: 100%;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
  background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
  margin-left: 60px;
}
<div style="text-align: center;">
<div class="switch">
  <input id="cmn-toggle-2" class="cmn-toggle cmn-toggle-round" type="checkbox">
  <label for="cmn-toggle-2"></label>
</div>
</div>