1.新建02.html文件,输入代码:
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>单项选择</title>
<style>
</style>
</head>
<body>
<script>
</script>
</body>
</html>
2.body
中在script
标签前面添加一个div
和两个span
元素,div中添加4个label
,4个label的id
属性值分别是a、b、c、d,class
属性值为off。
<div>
<label id="a" class="off"></label>
<label id="b" class="off"></label>
<label id="c" class="off"></label>
<label id="d" class="off"></label>
</div>
<span>你选的是:</span><span></span>
div
是一种容器元素,可以容纳其它的元素,如果多个div将分布在页面的多行,span
是行内容器元素,多个span处于页面的同一行。
3.在style中设置元素的css,包括label
,.on
,.off
。
<style>
label {
display: block;
border: solid 2px #666;
border-radius: 16px;
width: 24px;
height: 24px;
user-select: none;
text-align: center;
margin: 3px;
}
.on {
background-color: green;
color: white;
cursor: default;
}
.off {
background-color: #ccc;
cursor: pointer;
}
</style>
label{...}
是label标签的样式,.on{...}
是label标签叠加的选中
样式,.off{...}
是label标签叠加的非选中
样式。
4.在script
中添加脚本,定义question,answer,select三个变量
var question = document.getElementsByTagName('div')[0],
answer = document.getElementsByTagName('span')[1],
select
上述写法等同于下面的写法(注意var
和逗号
)
var question = document.getElementsByTagName('div')[0]
var answer = document.getElementsByTagName('span')[1]
var select
5.对question
对象添加鼠标点击事件
question.onclick = function (e) {
alert(e.target.id)
}
function (e)
中的e
是event的简写,是鼠标点击方法内置的参数,e.target
是question对象内(包含question对象本身)被鼠标单击的元素,e.target.id
是单击元素的id值。浏览器中,单击第三个,弹出提示c
,c就是第三个label的id值。
将上面的alert(e.target.id)
改成console.log(e.target)
,浏览器打开后按键盘F12
,选项卡切换到Console
,点击第二圆形的label,再点击四个圆后面任意空白位置,Console中依次出现<label id="b" class="off"></label>
(就是第二个圆形的label)和<div>...</div>
(就是名称为question的div容器元素)。
6.修改question.onclick
中的代码,添加if
条件判断。if的条件有两个e.target.innerHTML != '✔'
(!=
表示不相等)和e.target.id
(表示鼠标点中的元素存在id值,目的是排除div容器元素);&&
是逻辑与
,表示两个条件都要达到。
question.onclick = function (e) {
if (e.target.innerHTML != '✔' && e.target.id) {
console.log(e.target)
}
}
浏览器中按F12,通过Console查看结果。
7.在if中添加下列三行代码,浏览器测试三行代码的含义。
if (e.target.innerHTML != '✔' && e.target.id) {
e.target.innerHTML = '✔'
e.target.setAttribute('class', 'on')
answer.innerHTML = e.target.id.toUpperCase()
}
answer.innerHTML = e.target.id.toUpperCase()
后面再添加下列代码,并测试。
if (select) {
select.innerHTML = ''
select.setAttribute('class', 'off')
}
select = e.target
if中的完整代码如下:
if (e.target.innerHTML != '✔' && e.target.id) {
e.target.innerHTML = '✔'
e.target.setAttribute('class', 'on')
answer.innerHTML = e.target.id.toUpperCase()
if (select) {
select.innerHTML = ''
select.setAttribute('class', 'off')
}
select = e.target
}
最终效果
---------------------完-----------------------