如何使用切换滑块js

我正在尝试使用 html 中的滑块切换值,这是我所做的: html 文件:


    <!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script scr="./scripts.js" type="text/javascript"></script>

</head>

<body style="font-family: Calibri; font-size: 24px; font-style: normal; font-variant: normal; font-weight: 100; line-height: 26.4px;">

<div id="myDIV">Hello</div>


        <h2> Testing switch:

                <label class="switch">

                  <input id="status" type="checkbox" checked>

                  <span class="slider round" ></span>

              </h2>



</body>

这里是scripts.js我使用的代码:


function myFunction() {

  var x = document.getElementById("myDIV");

  var isChecked = document.getElementById("status");

  if (isChecked.checked ==true) {

    x.innerHTML = "Swapped text!";

  } else {

    x.innerHTML = "Hello";

  }

}

我不明白我错过了什么,但移动幻灯片不会改变文本!知道我该如何解决这个问题吗?提前致谢 !


翻阅古今
浏览 140回答 2
2回答

呼唤远方

您需要以某种方式触发您的功能。它不会自动运行。下面的示例通过myFunction在复选框使用onChange属性更改值时运行来修复该问题。function myFunction() {&nbsp; var x = document.getElementById("myDIV");&nbsp; var isChecked = document.getElementById("status");&nbsp; if (isChecked.checked == true) {&nbsp; &nbsp; x.innerHTML = "Swapped text!";&nbsp; } else {&nbsp; &nbsp; x.innerHTML = "Hello";&nbsp; }}<!DOCTYPE html><html><head>&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; <link rel="stylesheet" href="./layout.css">&nbsp; <script scr="./scripts.js" type="text/javascript"></script></head><body style="font-family: Calibri; font-size: 24px; font-style: normal; font-variant: normal; font-weight: 100; line-height: 26.4px;">&nbsp; <div id="myDIV">Hello</div>&nbsp; <h2> Testing switch:&nbsp; &nbsp; <label class="switch">&nbsp; &nbsp; <input id="status" type="checkbox" checked onChange="myFunction(this)">&nbsp; &nbsp; <span class="slider round" ></span>&nbsp; </h2></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript