猿问

如何使用按钮更改网站的背景?

我正在尝试编写一个需要使用按钮更改背景的网站,但我无法...


我创建了一个按钮,可以在单击按钮时更改背景颜色,但是在添加图像作为背景后,它不想更改背景颜色(显然)...


<head>

<style>

:root{

   --main-bg: url(https://www.the url of my bg.jpg);


}

</style> // creating a variable for the bg of my site


<style>

body {

   background: var(--main-bg) repeat-x;


}

</style> // using this variable


<script>

      var colors = ["#2d2d2d", "#f2f2f2"];

      var colorIndex = 0;

      function changeColor() {

          var col = document.getElementById("body");

          if( colorIndex >= colors.length ) {

              colorIndex = 0;

          }

          col.style.backgroundColor = colors[colorIndex];

          colorIndex++;

// the js script to change the bg color

      }

  </script>


<script>

      function backgroundHiding() {

         let root = document.documentElement;


         root.addEventListener("onclick", e => {

            if (--main-bg) =  "#2d2d2d" {

            root.style.setProperty('--main-bg', " url(https://www.the urlof my bg.jpg)")

         } else {

            root.style.setProperty('--main-bg', "#2d2d2d")

         }

            // the js script to hide my img bg

      }

      </script>


<div class="button">

      <body id='body'>

            <button onclick="changeColor(); backgroundHiding();" class="lightbutton"><span>Turn On/Off the lights</span> </button>


</div> // creating the button that interact with the two js functions

</head>

我预计它会起作用,但是......呃......不它有时有效,比如每 100 次 1 次,我不知道为什么......如果有人能帮助我,我会很感激!


https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html


手掌心
浏览 157回答 2
2回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答