Javascript 断电切换按钮/div

Javascript 断电切换按钮/div,javascript,css,Javascript,Css,我试图制作一个关机按钮(实际上是一个div),当我点击时,它会改变它的外观。 它看起来像一个中断器,所以我想更改页面的背景色,图标“关机”的颜色和按钮的边框样式 <body> <div class="interruptor"> <div id="io" class="poweroff"> <i class="fa fa-power-off"></i> </div> </div> <script src=

我试图制作一个关机按钮(实际上是一个
div
),当我点击时,它会改变它的外观。 它看起来像一个中断器,所以我想更改页面的
背景色
,图标“关机”的颜色和按钮的
边框样式

<body>
<div class="interruptor">
<div id="io" class="poweroff">
<i class="fa fa-power-off"></i>
</div>
</div>
  <script src="https://use.fontawesome.com/ddde7c70b6.js"></script>
  <script src="/js/logic.js" charset="utf-8"> </script>
  </body>
我从另一个站点获取了这个函数,它在添加一个CSS属性方面做得很好,但我希望它一直持续下去

document.getElementById('io').addEventListener('click', function () {
  if (this.classList.contains('poweroff')) {
  //  this.classList.remove('poweroff');
   this.classList.add('on');
  } else {
     this.classList.remove('on');
  }
});
我相信逻辑是这样的

x = x - 1
其中,
x
需要从
0
转到
1
,并从
1
转到
0
,每次单击该按钮

<body>
<div class="interruptor">
<div id="io" class="poweroff">
<i class="fa fa-power-off"></i>
</div>
</div>
  <script src="https://use.fontawesome.com/ddde7c70b6.js"></script>
  <script src="/js/logic.js" charset="utf-8"> </script>
  </body>

因为您是在关闭电源的基础上进行检查的,所以您也需要像这样切换它

document.getElementById('io').addEventListener('click', function () {
if (this.classList.contains('poweroff')) {
  this.classList.remove('poweroff');
  this.classList.add('on');
} else {
  this.classList.add('poweroff');
  this.classList.remove('on');
}
});
不要检查
if
条件并添加和删除类,而是使用如下切换

document.getElementById('io').addEventListener('click', function () {
if (this.classList.contains('poweroff')) {
  this.classList.remove('poweroff');
  this.classList.add('on');
} else {
  this.classList.add('poweroff');
  this.classList.remove('on');
}
});


您应该使用切换而不是添加和删除,如下所示:

 document.getElementById('io').addEventListener('click', function () {
  if (this.classList.contains('poweroff')) {
     this.classList.toggle('poweroff');
     this.classList.toggle('on');
  } else {
    this.classList.toggle('on');
  }
});

通过这种方式,它将在单击按钮时自动添加和删除类。

请将您的HTML和CSS也分享给我们,请不要将其作为注释。为什么您不使用适当的
?按钮样式的可能重复与div样式没有区别,只是按钮有一些内置样式。然而,
在语义上是正确的,而
在语义上是不正确的!