使用 HTML5 & CSS 实现一个自定义开关按钮 switch button
阅读原文时间:2023年07月08日阅读:2

使用 HTML5 & CSS 实现一个自定义开关按钮 switch button

  <div class="switch">
    <input class="switch-checkbox" id="btn_switch" type="checkbox">
    <label class="switch-label" for="btn_switch">
      <span class="switch-inner" data-on="ON" data-off="OFF"></span>
      <span class="switch-switch"></span>
    </label>
  </div>


.switch {
  position: relative;
  float: left;
  width: 90px;
  margin: 0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.switch-checkbox {
  display: none;
}

.switch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #999999;
  border-radius: 20px;
}

.switch-inner {
  display: block;
  width: 200%;
  margin-left: -100%;
  transition: margin 0.3s ease-in 0s;
}

.switch-inner::before,
.switch-inner::after {
  display: block;
  float: right;
  width: 50%;
  height: 30px;
  padding: 0;
  line-height: 30px;
  font-size: 14px;
  color: white;
  font-family:  Trebuchet, Arial, sans-serif;
  font-weight: bold;
  box-sizing: border-box;
}

.switch-inner::after {
  content: attr(data-on);
  padding-left: 10px;
  background-color: #00e500;
  color: #FFFFFF;
}

.switch-inner::before {
  content: attr(data-off);
  padding-right: 10px;
  background-color: #EEEEEE;
  color: #999999;
  text-align: right;
}

.switch-switch {
  position: absolute;
  display: block;
  width: 22px;
  height: 22px;
  margin: 4px;
  background: #FFFFFF;
  top: 0;
  bottom: 0;
  right: 56px;
  border: 2px solid #999999;
  border-radius: 20px;
  transition: all 0.3s ease-in 0s;
}

.switch-checkbox:checked+.switch-label .switch-inner {
  margin-left: 0;
}

.switch-checkbox:checked+.switch-label .switch-switch {
  right: 0px;
}

原理分析,使用 <label> 标签配合<input type=checkbox /> 复选框来实现的;

由于 label 的 for 属性会绑定到指定的 input 上,所以当点击 label 时会间接触发隐藏的 input 的 checkbox 切换,从而动态切换开关的状态;

https://codepen.io/xgqfrms/pen/qBNGGVv

See the Pen HTML5 & CSS (switch button) by xgqfrms
(@xgqfrms) on CodePen.

https://developer.mozilla.org/en-US/docs/Web/CSS/attr()

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

article::before {
  content: attr(data-parent);
}



<article
  id="electric-cars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

CSS 函数

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Functions

https://caniuse.com/dataset

HTML5 dataset All In One

https://www.cnblogs.com/xgqfrms/p/13747905.html

https://www.sitepoint.com/how-why-use-html5-custom-data-attributes/

https://css-tricks.com/a-complete-guide-to-data-attributes/



xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章