首页 > 解决方案 > 如何在两组文本之间进行切换更改?

问题描述

我正在尝试在两组文本之间进行切换栏更改。我已经让开关和滑块正常工作,但不知道如何将功能连接到滑块。

我使用 W3School 制作了测试环境:

https://www.w3schools.com/code/tryit.asp?filename=FVEFVIB1J6D2

开关代码的格式正确,但它没有采用图形的格式。

function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.innerHTML === "Longer text") {
        x.innerHTML = "Shorter text";
    } else {
        x.innerHTML = "Longer text";
    }
}
.switch {
  position: relative;
  display: inline-block;
  width: 90px;
  height: 34px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #009bff;
  -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: #2ab934;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(55px);
  -ms-transform: translateX(55px);
  transform: translateX(55px);
}


/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<p>
  <switch onclick="myFunction()">Choose your lenght </switch>
</p>        
<label class="switch">
  <input type="checkbox">
  <span class="slider round"></span>
</label>
<div id="myDIV">Longer Story</div>

标签: javascripthtml

解决方案


你快完成了。您所要做的就是在类中添加一个onClick回调,如下所示:spanslider round

<label class="switch">
  <input type="checkbox">
  <span class="slider round" onclick='myFunction()'></span>
</label>

推荐阅读