版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caishu1995/article/details/88536566
感谢程梦君童鞋,之前我只是知道用label是用于展示文字的。有时候用label也仅是用于给文字加样式,还没有发现,label的另外一个属性的妙用。
比如这个表单,我们想必须点击radio控件,才能选中。后来有人觉得麻烦,我们要点文字,也能控制控件选中,怎么办呢?我们可能会加js,控制,当我们点击文字,执行函数,在函数里选中radio。但如果我们发现label还有一个for属性,我们就会发现我们完全不用这么麻烦。
<html>
<head>
<title>for属性测试</title>
</head>
<body>
<form>
<label for="male">Male</label>
<input type="radio" name="sex" id="male" value="0"/>
<br />
<label for="female">Female</label>
<input type="radio" name="sex" id="female" value="1"/>
</form>
</body>
</html>
现在,我们只要点击文字,输入框就能自动被选中呢?惊奇么?for后面跟的是控件的id。
当我们发现了这个good属性,我们就可以简化另一个功能。
功能如下:自建单选控件,类似这种。当我们选择male会有样式提醒,同时方便于我们取值。
之前的做法:设置两个label,制作成如图的样子,然后再加两个隐藏的radio控件。当我们点击male的时候,给male所在的label加样式,同时让male说对应的radio被选中。
现在的做法:设置两个label,制作成如图的样子,然后再加两个隐藏的radio控件。当我们点击male的时候,给male所在的label加样式,同时让male说对应的radio被选中。
是不是省了一步?代码如下
<html>
<head>
<title>for属性测试</title>
<style>
.selected{ background: green; color: white; }
</style>
</head>
<body>
<span style="border: 1px solid #c5c5c5; border-radius: 10px; float: left; overflow: hidden;">
<label for="male" style="float: left; height: 20px; padding: 5px 10px; " class="selected" onclick="changeSex(this)">Male</label>
<label for="female" style="float: left; height: 20px; padding: 5px 10px;" onclick="changeSex(this)">Female</label>
</span>
<input type="radio" name="sex" id="male" value="0" checked/>
<input type="radio" name="sex" id="female" value="1" />
<script>
function changeSex(_this){
_this.parentNode.getElementsByClassName("selected")[0].classList.remove("selected");
_this.classList.add("selected");
}
</script>
</body>
</html>
当我们选中male。当我们选中female
代码量更省哦。