01.按钮开关

1.vscode中新建文件01.html,输入代码

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>hello</title>
    <style>
    </style>
</head>
<body>
    <script>
    </script>
</body>
</html>

2.在body中添加label标签元素,label中输入文本ON

<body>
    <label>ON</label>
    <script>
    </script>
</body>

3.给label添加css样式

<style>
    label {
         display: inline-block;
         padding: 5px 10px;
         border: solid 2px #666;
         border-radius: 20px;
         width: 60px;
         cursor: pointer;
         user-select: none;
         background-color: green;
         color: white;
     }
</style>

浏览器打开01.html,显示如下
在这里插入图片描述
4.书写script交互代码

<script>
        var btn = document.getElementsByTagName('label')[0]
        btn.onclick = function () {
            if (btn.innerHTML == 'ON') {
                btn.innerHTML = 'OFF'
            } else if (btn.innerHTML == 'OFF') {
                btn.innerHTML = 'ON'
            }
        }
</script>

在这里插入图片描述
5.给label添加class="on"属性,style中进行相应的修改

<label class="on">ON</label>
<style>
    label {
        display: inline-block;
        padding: 5px 10px;
        border: solid 2px #666;
        border-radius: 20px;
        width: 60px;
        cursor: pointer;
        user-select: none;
    }
    .on {
        background-color: green;
        color: white;
    }
    .off {
        background-color: #ccc;
        text-align: right;
    }
</style>

6.对js中的if语句进行修改,添加btn.setAttribute方法

if (btn.innerHTML == 'ON') {
    btn.innerHTML = 'OFF'
    btn.setAttribute('class','off')
} else if (btn.innerHTML == 'OFF') {
    btn.innerHTML = 'ON'
    btn.setAttribute('class','on')
}

最终完成的效果
在这里插入图片描述
---------------------完---------------------

发布了30 篇原创文章 · 获赞 2 · 访问量 6420

猜你喜欢

转载自blog.csdn.net/yaochaohx/article/details/104210623
01.