JavaScript使用数据实现切换开关

3
我一直在尝试创建一个开关,以启用/禁用程序的某个部分。我用来创建按钮的代码是从这里w3schools中获取的。
现在我想要向该按钮添加功能,但是完全卡住了。我的意图是,如果按下开关,我希望我的程序激活部分代码,从而启用设置;或者如果开关已经打开,则将其禁用。
所以我正在寻找一种方法在某处获取开关的值,并在类似于if语句的东西中使用它,例如:
if(switch== on){ 
   //do this;
} else{ 
   //do that;
}

我希望我的意思表达清楚了。非常感谢您的帮助。

5个回答

14

我不确定这是否符合您的要求,但通常情况下,您希望监听一个事件,在选中状态更改时触发:

我不知道那是否是你想要的,但通常情况下,你需要监听一个事件,当被选中的状态改变时触发:

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');
    }
  });
});
.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);
}
<h2>Toggle Switch</h2>

<label class="switch">
  <input type="checkbox">
  <div class="slider"></div>
</label>

当浏览器解析您的HTML并到达<script>标记时,它立即执行其中的JavaScript代码。但是有可能出现这种情况,即文档其余部分尚未加载。
这意味着页面中的某些HTML元素尚不存在,因此无法在JavaScript中访问它们。您必须等待元素加载完成。
幸运的是,当浏览器完成页面内容加载时,会触发一个事件。该事件称为DOMContentLoaded
等待浏览器首先触发事件时,您可以确保能够访问DOM中的所有元素。

我已经尝试过这个,如果我检查控制台,会出现一个错误消息,说它无法读取属性addEventListener。在那里控制台也没有显示任何内容。我对使用javascript还比较新,所以不知道该怎么做。你能推荐一种方法来消除这个错误吗?或者给我一些东西,当我点击它时在网页上显示? - JoJoDeath
这取决于你如何加载JavaScript。当我发布的代码运行时,必须加载复选框元素。如果没有加载,document.querySelector将返回null,并且您无法读取null的属性。使用我的更新后的答案应该可以解决这个问题。 - PeterMader
啊是的,现在它可以工作了。第一行代码现在到底是做了什么?我很好奇它到底做了什么,为什么它让它运行起来了。 - JoJoDeath
所以我一直在处理网页的其他部分,但是发现了一个问题,不知道该如何解决:当我将开关打开时,它会变成开启状态,但是如果我转到另一页,然后返回带有滑块的页面,它实际上又处于“关闭”位置。我认为我需要根据开关的值(ProgramState="on"或"off")来显示其位置,但我不知道该怎么做。你有什么提示/想法可以让这个工作吗? - JoJoDeath
打算说浏览器重新打开时,复选框的状态没有被记住吗? - PeterMader
它确实记住我给它的值。当我按下开关时,它会打开,并更改ProgramState的值。这个值被记住了,所以结果是相同的。但是开关的可视化效果会回到正常状态:处于“关闭”位置,即使ProgramState的值为“开”。我想知道如何使网页检查值,并根据值将开关显示在左侧或右侧(分别为“关闭”和“开”值)。 - JoJoDeath

3

使用复选框元素的checked值来查看当前状态。

另请参见Oded在此帖子中关于HTML属性用法的答案

在JavaScript中,您可以以任何喜欢的方式检索元素,然后简单地查看checked属性的值。

工作示例:

function getValue() {
   var isChecked = document.getElementById("myCheckBox").checked;
    
   if(isChecked){
     console.log("Input is checked");
   } else {
     console.log("Input is NOT checked");
   }
}
<label>
  <input id="myCheckBox" type="checkbox" > Toggle me
</label>

<br>
<br>

<button onclick="getValue()">Check value of above input</button>


2
你可以使用 JQuery 来解决这个问题。 将一个改变事件附加到输入复选框元素。
<input type="checkbox" id="myToggle"/>

$('#myToggle').change(function(){
    if(this.checked) {
        do this;
    }
    else {
        do that;
    }
});

2
这是一个非常基本的例子:

function doStuff() {
    console.log("Hello World!")
}
function toggle(button) {
    if(button.value=="OFF") {
        button.value="ON"
        button.innerHTML="ON"
        this.interval = setInterval(doStuff, 1000);
    } else if(button.value=="ON") {
        button.value="OFF"
        button.innerHTML="OFF"
        clearInterval(this.interval)
    }
}
<button onclick="toggle(this)" value="OFF">OFF</button>


1

这只是一个复选框。你可以像这样做 ->

$(document).ready(function(){
 $('#on').on('change',function(){
     if(this.checked){
      $("#info").text("U checked me, place some code here");
     }
        else{
         $("#info").text("U unchecked me, another piece of code here");
        }
    });
});
.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%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
  <input id="on" type="checkbox">
  <div class="slider"></div>
</label>
<p id="info"></p>

只需将您的代码片段放置在if-else块中即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接