从切换按钮中删除javascript

问题描述 投票:0回答:2

这是当前切换按钮的代码。我想通过使用复选框删除它的javascript组件。我唯一的要求是我必须使用单个html元素来实现这一目标。

这是代码示例:

document.querySelector('.toggler').addEventListener('click', function(e) {
  this.classList.toggle('active');
});
.toggler {
  width: 140px;
  height: 40px;
  background-color: #B3B3B3;
  color: #FFF;
  clear: both;
  border-radius: 5px;
  font-size: 12px;
  /* new styles here: */
  padding: 0 0 0 24px;
  box-sizing: border-box;
  display: inline-block;
  position: relative;
  line-height: 40px;
  text-align: center;
  cursor: pointer;
  transition: padding .25s ease;
}

.toggler.active {
  padding: 0 24px 0 0;
}

.toggler:before {
  content: '';
  display: block;
  width: 20px;
  height: 36px;
  background-color: #4D4D4D;
  position: absolute;
  left: 2px;
  top: 2px;
  border-radius: 5px;
  /* transition to make it look smoother */
  transition: left .4s ease;
}

.toggler.active:before {
  left: calc(100% - 22px);
}
<div class="toggler">Text Value</div>

的jsfiddle:https://jsfiddle.net/3bfzagpm/2/

我能用<input type="checkbox" class="toggler">Text Value</input>做到这一点吗?

编辑:

为了更具体我想要的东西,我希望按钮的切换没有任何javascript组件。这应该只是CSS和HTML。我还想维护一个html元素来完成这个。

html css html5 css3
2个回答
3
投票

正如你在上一篇文章中所提到的,只有一个复选框才能实现它,因为复选框不能有content,因此没有伪元素::before::after,因为它们都在content上运行。

.togglerCheckbox {
  display: none; }

.toggler {
  width: 140px;
  height: 40px;
  background-color: #B3B3B3;
  color: #FFF;
  clear: both;
  border-radius: 5px;
  font-size: 12px;
  /* new styles here: */
  padding: 0 0 0 24px;
  box-sizing: border-box;
  display: inline-block;
  position: relative;
  line-height: 40px;
  text-align: center;
  cursor: pointer;
  transition: padding .25s ease;
}

.togglerCheckbox:checked + .toggler {
  padding: 0 24px 0 0;
}

.toggler:before {
  content: '';
  display: block;
  width: 20px;
  height: 36px;
  background-color: #4D4D4D;
  position: absolute;
  left: 2px;
  top: 2px;
  border-radius: 5px;
  /* transition to make it look smoother */
  transition: left .4s ease;
}

.togglerCheckbox:checked + .toggler:before {
  left: calc(100% - 22px);
}
<input type="checkbox" id="mycheckbox" class="togglerCheckbox" /><label for="mycheckbox" class="toggler">Text Value</label>

0
投票

要获得预期的结果,您可以尝试以下选项CSS:

#toggle:checked + .toggler:before{
  left: calc(100% - 22px);
}

HTML:

<input type="checkbox" name="toggle" id="toggle" />
<div class="toggler">Text Value</div>

https://codepen.io/nagasai/pen/aqMbym

© www.soinside.com 2019 - 2024. All rights reserved.