Using js to Realize Simple Switch Lamp Code

  • 2021-12-09 08:12:02
  • OfStack

body section:


<button> Switch lamp </button>

script section:


    <script>

        // window.onload  Is a window load event, which can write code to the element 

        window.addEventListener('load', function () {

            var btn = document.querySelector('button');

            //  Definition 1 Variable, used to judge the switch condition of the lamp 

            var flag = 0;

            btn.onclick = function () {

                if (flag == 0) {

                    document.body.style.backgroundColor = 'black';

                    flag = 1;

                } else {

                    document.body.style.backgroundColor = 'pink';

                    flag = 0;

                }

            }

        })

    </script>

If script Write directly to button The following words,

The following code is used:


<script>

        var btn = document.querySelector('button');

        var flag = 0;

        btn.onclick = function () {

            if (flag == 0) {

                document.body.style.backgroundColor = 'black';

                flag = 1;

            } else {

                document.body.style.backgroundColor = 'pink';

                flag = 0;

            }

        }

    </script>
 

Related articles: