label元素作用总结

label与input关联机制

label用来关联一个表单元素,实现代码如下:

<label for="gender">性别</label>
<input id="gender" type="checkbox"  value="0">

模拟button

利用label”模拟”button来解决不同浏览器原生button样式不同的问题

实现代码如下:

<input type="button" id="btn">
<label for="btn">Button</label>

<style>
input[type='button'] {
  display: none;
}

label {
  display: inline-block;
  padding: 10px 20px;
  background: #456;
  color: #fff;
  cursor: pointer;
  box-shadow: 2px 2px 4px 0 rgba(0,0,0,.3);
  border-radius: 2px;
}
</style>

结合CSS状态切换

结合checkboxradio表单元素实现纯CSS状态切换,这样的实例就太多了。比如控制CSS动画播放和停止。下面是一部分代码。详细实例地址

<input type="checkbox" id="controller">
<label class="icon" for="controller">
  <div class="play"></div>
  <div class="pause"></div>
</label>
<div class="animation"></div>

<style>
...
#controller:checked ~ .animation {
  animation-play-state: paused;
}
...
</style>

label实现选项卡切换

input的focus事件会触发锚点定位,我们可以利用label当触发器实现选项卡切换效果。下面代码选自张鑫旭《CSS世界》。项目链接

<div class="box">
  <div class="list"><input id="one" readonly>1</div>
  <div class="list"><input id="two" readonly>2</div>
  <div class="list"><input id="three" readonly>3</div>
  <div class="list"><input id="four" readonly>4</div>
</div>
<div class="link">
  <label class="click" for="one">1</label>
  <label class="click" for="two">2</label>
  <label class="click" for="three">3</label>
  <label class="click" for="four">4</label>
</div>

<style>
.box {
  width: 20em;
  height: 10em;
  border: 1px solid #ddd;
  overflow: hidden;
}
.list {
  height: 100%;
  background: #ddd;
  text-align: center;
  position: relative;
}
.list > input { 
  position: absolute; top:0; 
  height: 100%; width: 1px;
  border:0; padding: 0; margin: 0;
  clip: rect(0 0 0 0);
}
</style>

 

(0)
上一篇 2019年9月2日 下午11:28
下一篇 2019年9月3日 下午2:05

相关推荐

发表回复

登录后才能评论