单击一次将元素设置为白色,再次单击一次将元素设置为红色



我有一个关于让元素变成白色的问题,一旦再次单击就会变成红色。我使用铬。另外,我不明白我是如何做到这一点的,所以我希望收到详细的答复。

<html>
  <head>
    <script>
        var color = document.querySelectorAll('h1')
        color.onclick = function(){
          if (this.style.backgroundColor == 'red') {
            this.style.backgroundColor = 'white'
            this.style.color = 'white'
          }
          if (this.style.backgroundColor == 'blue') {
            this.style.backgroundColor = 'white'
            this.style.color = 'white'
          }
          if (this.style.backgroundColor == 'white') {
            this.style.backgroundColor = 'red'
            this.style.color = 'red'
          }
        }
    </script>
  </body>
</html>

(编辑)很抱歉我没有添加片段,我正在编辑中添加这个片段。我希望有一个更详细的解释,谢谢。我试图在谷歌上搜索,在这个网站上搜索,并问这个问题。(编辑)

如果没有一些示例代码,要准确确定您要执行的操作有点困难,但是如果我了解您要正确执行的操作,那么您正在尝试在单击时替换背景颜色。

首先,您要选择页面上的元素。然后应用单击处理程序。在此单击处理程序中,您希望使用 style 属性检查条件中的背景颜色。如果颜色为红色,则将其设置为白色。如果颜色不是红色,则将其设置为红色。

这可以在以下示例中看到:

var example = document.getElementById('example');
example.onclick = function() {
  if (this.style.backgroundColor == 'red') {
    this.style.backgroundColor = 'white'
  }
   else {
     this.style.backgroundColor = 'red'
   }
}
<div id="example">Text</div>

希望这有帮助! :)

最新更新