当用户选择该标签时,浏览器就会自动将焦点转到和标签相关的表单控件上。
绑定方法:通过label标签的for属性与相关表单控件的id属性相同
eg:
<label for="test">姓名</label>
<input type="text" id="test" />
1.label与input(type="text")文本类型的结合
当鼠标点击姓名是,光标自动定位到input输入框,如下图
2.label与input(type="radio")按钮类型的结合
与此类型结合,一般用来重置按钮样式或解决手机端选项点击不灵活现象
-
重置按钮样式
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>按钮列表</title>
<style type="text/css">
body{
margin:0;
padding:0;
}
#container{
width:500px;
margin: 0 auto;
height:500px;
}
.radio-item{
position:relative;
}
.radio-item .radio-text{
position:relative;
top:-6px;
display: inline-block;
}
input{
width:20px;
height: 20px;
opacity: 0;
}
input+label{
position:absolute;
left:4px;
top:2px;
width: 20px;
height: 20px;
/*border-radius: 50%;*/
border: 1px solid #f2f2f2;
}
input:checked+label{
background:#999;
border:1px solid #999;
}
input:checked+label:after{
position: absolute;
left: 7px;
top: 2px;
content: "";
width: 5px;
height: 12px;
border: 2px solid #fff;
border-left: none;
border-top: none;
transform: rotate(45deg);
}
</style>
<script type="text/javascript" src="../vendor/jquery-1.11.3.min.js" ></script>
</head>
<body>
<div id="container">
<div class="radio-item">
<input type="checkbox" id="item1" name="item1" checked/>
<label for="item1"></label>
<label for="item1" class="radio-text">选项一</label>
</div>
<div class="radio-item">
<input type="checkbox" id="item2" name="item1"/>
<label for="item2"></label>
<label for="item2" class="radio-text">选项二</label>
</div>
<div class="radio-item">
<input type="checkbox" id="item3" name="item1" checked/>
<label for="item3"></label>
<label for="item3" class="radio-text">选项三</label>
</div>
<div class="radio-item">
<input type="checkbox" id="item4" name="item1"/>
<label for="item4"></label>
<label for="item4" class="radio-text">选项四</label>
</div>
</div>
<script>
$(document).ready(function(){
});
</script>
</body>
</html>
-
解决手机端点击不灵活现象
例如单选题,用的都是radio类型,由于在手机端,屏幕宽度有限,所以按钮点击事件就没有像在电脑端那么准确,如果我们利用label的for属性与input的id属性绑定,这样,再点击选择的时候,只要点击下当前的题目就可以选中,没必要非得去单独点击按钮了。