编程语言
首页 > 编程语言> > JAVAScript 灯泡(开关,图片转换)

JAVAScript 灯泡(开关,图片转换)

作者:互联网

方案一   单按钮(开 / 关)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>修改灯泡</title>

    <style>

        img{

            width: 200px;

            height: 300px;

       

        }

    </style>

</head>

<body>

    <img src="../images/dark.jpg" alt="">

    <button>开灯</button>

    <script>

        var img = document.getElementsByTagName('img')[0];

        var btn = document.getElementsByTagName('button')[0];

        var tag = true;

        btn.onclick = function () {

            if (tag) {

                img.src = '../images/bright.jpg';

                btn.innerText = '关灯';

            } else {

                img.src = '../images/dark.jpg';

                btn.innerText = '开灯';

            }

            tag = !tag;

        }

    </script>

</body>

</html>

方案二  双按钮(开    关)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>灯泡</title>

   

</head>

<body>

    <div class="box">

        <img src="../images/bark.jpg" alt="">

        <button>开</button>

        <button>关</button>

    </div>

    <script>

        var box_img = document.getElementsByClassName('box')[0].getElementsByTagName("img")[0];

        var box_btn = document.getElementsByClassName('box')[0].getElementsByTagName("button");

        box_btn[0].onclick = function () {

            box_img["src"] = "../images/light.jpg";

        }

        box_btn[1].onclick = function () {

            box_img.src = "../images/bark.jpg";

        }

    </script>

</body>

</html>

标签:box,img,JAVAScript,灯泡,开关,tag,jpg,var,btn
来源: https://blog.csdn.net/m0_62791728/article/details/121123993