首页 > 解决方案 > 如何使 JavaScript 'getElementById' 在 HTML CSS Toggle Switch 上工作

问题描述

我需要使用 JavaScript 激活我的 HTML/CSS 'Toggle Switch'。

我希望默认情况下隐藏带有文本的 DIV,当滑块(切换器)向左滑动时,它会“触发”DIV 以使用 JavaScript“显示”。

我怎么知道我走在正确的道路上,但是我的行为有些不对劲……

function toggleDiv() {
  var triggeredDiv = document.querySelector('.triggeredDiv');
  if (document.getElementById('flipswitch').checked) {
    triggeredDiv.classList.remove('shown');
  } else {
    triggeredDiv.classList.add('shown');
  }
}

document.getElementById('flipswitch').addEventListener("change", toggleDiv);
.flipswitch {
  position: relative;
  width: 200px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.flipswitch input[type=checkbox] {
  display: none;
}

.flipswitch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #999999;
  border-radius: 50px;
}

.flipswitch-inner {
  width: 200%;
  margin-left: -100%;
  -webkit-transition: margin 0.3s ease-in 0s;
  -moz-transition: margin 0.3s ease-in 0s;
  -ms-transition: margin 0.3s ease-in 0s;
  -o-transition: margin 0.3s ease-in 0s;
  transition: margin 0.3s ease-in 0s;
}

.flipswitch-inner:before,
.flipswitch-inner:after {
  float: left;
  width: 50%;
  height: 60px;
  padding: 0;
  line-height: 60px;
  font-size: 18px;
  color: white;
  font-family: Trebuchet, Arial, sans-serif;
  font-weight: bold;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.flipswitch-inner:before {
  content: "MONTHLY";
  padding-left: 12px;
  background-color: #FFFFFF;
  color: #888888;
  font-family: 'Montserrat', sans-serif;
  font-weight: 400;
}

.flipswitch-inner:after {
  content: "BY COUNTRY";
  padding-right: 12px;
  background-color: #EBEBEB;
  color: #888888;
  text-align: right;
  font-family: 'Montserrat', sans-serif;
  font-weight: 400;
}

.flipswitch-switch {
  width: 45px;
  margin: 7.5px;
  background: #FFFFFF;
  border: 2px solid #999999;
  border-radius: 50px;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 139px;
  -webkit-transition: all 0.3s ease-in 0s;
  -moz-transition: all 0.3s ease-in 0s;
  -ms-transition: all 0.3s ease-in 0s;
  -o-transition: all 0.3s ease-in 0s;
  transition: all 0.3s ease-in 0s;
}

.flipswitch-cb:checked+.flipswitch-label .flipswitch-inner {
  margin-left: 0;
}

.flipswitch-cb:checked+.flipswitch-label .flipswitch-switch {
  right: 0;
}

.triggeredDiv {
  display: none;
}

.triggeredDiv.shown {
  display: block;
}
<div class="flipswitch">
  <input type="checkbox" name="flipswitch" class="flipswitch-cb" id="fs" checked>
  <label class="flipswitch-label" for="fs">
    <div class="flipswitch-inner"></div>
    <div class="flipswitch-switch"></div>
  </label>
</div>

<div class="triggeredDiv">
  Show Text
</div>

标签: javascripthtmlcss

解决方案


这里的问题是你试图通过一个flipswitch的id来引用flipswitch,而你给这个开关的id是fs。只需将 javascript 中的引用更改为:

document.getElementById('fs')

代替

document.getElementById('flipswitch')

推荐阅读