快速掌握—HTML快速实现自定义Input开关

file

HTML

<input id="customSwitch" type="checkbox" />
<label for="customSwitch" class="switch"></label>

CSS

/* 定义全局变量 */
:root {
  --base_color: rgba(0, 0, 0, 0.25);
  --act_color: #5dcb61;
}

/* 隐藏input输入框 */
#customSwitch {
    position: absolute;
    left: -9999px;
}

/* 设置自定义颜色 */
.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  background-color: var(--base_color);
  border-radius: 20px;
  transition: all 0.3s 0s;
}
/* 开关圆球 */
.switch::after {
  content: "";
  position: absolute;
  top: 1px;
  left: 1px;
  width: 18px;
  height: 18px;
  border-radius: 18px;
  background-color: white;
  transition: all 0.3s 0s;
}

input[type="checkbox"]:checked   .switch::after {
  transform: translateX(20px);
}

input[type="checkbox"]:checked   .switch {
  background-color: var(--act_color);
}

核心知识点

  1. 隐藏真实input输入框,通过label for属性与input输入框绑定。
  2. label标签本身作为椭圆形背景,用伪类作为开关圆球。
  3. input选中后,需要单独设置label标签本体和伪类的移动

🌟本系列旨在通过最直接的事例最完整的代码,解决一些开发中常遇到的实际问题。

例子链接🚀:https://github.com/TianYiYang0225/high-ku/tree/master/customSwitch

喜欢的朋友可以点击关注一波~每天都会更新最实用的项目技巧

如果你觉得这篇文章帮助到了你,我很高兴。关注【前端小白的成长记录】每天都能看到虽然很【短】但是很【实用】的文章。后台回复你想看的资料,比如React。我会找到相关的【视频】和【电子书】发给你。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值