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')
}
最终完成的效果
---------------------完---------------------