02.单项选择

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中添加下列三行代码,浏览器测试三行代码的含义。

扫描二维码关注公众号,回复: 9561286 查看本文章
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
}

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

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

猜你喜欢

转载自blog.csdn.net/yaochaohx/article/details/104223276