JoJ*_*ath 0 html javascript css
我一直试图制作一个切换开关来启用/禁用我的程序的一部分.我用来制作按钮的代码来自w3schools
现在我想将功能添加到按钮,但完全卡住了.我想要做的是,如果按下开关,我希望我的程序激活我的代码的一部分,启用设置,或者如果开关已经打开,则禁用它.
所以我正在寻找的是一种在某处获取开关值的方法,并在if语句中使用它,例如:
if(switch== on){
//do this;
} else{
//do that;
}
Run Code Online (Sandbox Code Playgroud)
我希望很清楚我想说的是什么.任何帮助表示赞赏.
我不知道这是否是您想要的,但通常,您希望监听在检查状态发生变化时触发的事件:
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
// do this
console.log('Checked');
} else {
// do that
console.log('Not checked');
}
});
});Run Code Online (Sandbox Code Playgroud)
.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);
}Run Code Online (Sandbox Code Playgroud)
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox">
<div class="slider"></div>
</label>Run Code Online (Sandbox Code Playgroud)
当浏览器解析您的HTML并到达<script>标记时,它会立即执行其中的JavaScript.然而,可能发生的是,文档的其余部分尚未加载.
这意味着页面中的某些HTML元素尚不存在,您无法在JavaScript中访问它们.您必须等到元素加载.
幸运的是,浏览器在加载页面内容时会触发事件.此事件被调用DOMContentLoaded.
当您等待浏览器首先触发事件时,您可以确保可以访问DOM中的所有元素.
| 归档时间: |
|
| 查看次数: |
13537 次 |
| 最近记录: |