onclick 切换开关 [英] onclick on toggle switch
本文介绍了onclick 切换开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 W3Schools 的这个切换开关(链接:toggleswitch W3Schools )
I'm using this toggle switch by W3Schools (link : toggleswitch W3Schools )
我想在切换开关被选中时执行一个函数.
and i want to execute a function when the toggle switch is checked.
问题是当我使用 click 时,该函数执行了两次.它显示两次警报(顺便说一句,您可以尝试代码段)
The problem is that when i used on click , the function executed twice. it displays the alert twice (you can try the snippet btw)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.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" onclick="function1()">
<input type="checkbox">
<span class="slider"></span>
</label>
</body>
</html>
<script>
function function1(){
alert("heelloo");
}
</script>
我该怎么做才能正确调用该函数?
what can i do to make the call to the function properly ?
推荐答案
将函数下移到 Input
Move the function down to the Input
<input type="checkbox" onclick="function1()">
工作演示
function function1() {
alert("heelloo");
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.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%;
}
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox" onclick="function1()">
<span class="slider"></span>
</label>
</html>
<script>
</script>
这篇关于onclick 切换开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文