我跟随W3Schools的一个例子。添加CSS后,这会创建一个非常漂亮的按钮。我在哪里添加" onclick"我尝试了几个地方但没有工作。我试图调用一个名为myfuction()的函数,但它没有采用任何参数。
<label class="switch">
<input type="checkbox" checked>
<div class="slider round"></div>
</label>
这里有完整的例子.. W3Schools "How to Create a Toggle Switch"
答案 0 :(得分:1)
您可以将onclick事件放在输入类型
中<input type="checkbox" checked onclick="myfuction()">
JS
function myfuction(){
alert("hi")
}
答案 1 :(得分:1)
$(function() {
$(document).on('click', '.switch', function(){
myFunction();
});
});
function myFunction()
{
alert('Here');
}
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox" checked>
<div class="slider round"></div>
</label>
</body>
</html>
&#13;
答案 2 :(得分:0)
您可以使用jquery事件将标签绑定到click事件
通过类
访问标签$(".switch").click(function(){
myFunction();
});
答案 3 :(得分:0)
绑定到change
事件而不是click
。但是,您可能仍需要检查复选框是否已选中:
$(document).ready(function() {
$('input[type=checkbox]').change(function() {
console.log("checkbox changed");
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
.switch{position:relative;display:inline-block;width:60px;height:34px}.switch input{display:none}.slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#ccc;-webkit-transition:.4s;transition:.4s}.slider:before{position:absolute;content:"";height:26px;width:26px;left:4px;bottom:4px;background-color:#fff;-webkit-transition:.4s;transition:.4s}input:checked+.slider{background-color:#2196F3}input:focus+.slider{box-shadow:0 0 1px #2196F3}input:checked+.slider:before{-webkit-transform:translateX(26px);-ms-transform:translateX(26px);transform:translateX(26px)}.slider.round{border-radius:34px}.slider.round:before{border-radius:50%}
</style>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox" checked>
<div class="slider round"></div>
</label>
</body>
</html>
&#13;
请检查上面的代码段吗?