css写一个原生switch开关按钮

在这里插入图片描述










<!DOCTYPE html>
<html>
<head>
    <title>switch开关按钮</title>
    <style type="text/css">
#checked {
 width: 60px;
 position: relative;
 margin: 20px auto;
}
.labelBox {
 margin-bottom: 20px;
 background: #409eff;
 border-radius: 40px;
 width: 60px;
 position: relative;
 height: 32px;
}
.check {
 display: block;
 width: 30px;
 height: 30px;
 border-radius: 50%;
 background: #fff ;
 border: 1px solid #e5e5e5;
 position: absolute;
 top: 0px;
 left: 0px;
}
input[type=checkbox] {
 border: 0 none !important;
 clip: rect(1px,1px,1px,1px);
 height: 1px !important;
 overflow: hidden !important;
 position: absolute !important;
 width: 1px !important;
}

@keyframes labelON {
 0% {
  top: 0px;
  left: 0px;
 }    
 100% {
  top: 0px;
  left: 28px;
 }
}

更多请见:http://www.mark-to-win.com/tutorial/50956.html

CSS3实现一个滑动开关按钮效果是一种常见而优雅的方式,它需要借助JavaScript即可完成交互体验。以下是其实现原理及关键点: ### 实现步骤 1. **HTML结构** 使用`<input>`标签配合隐藏的复选框(checkbox),并结合 `<label>` 来控制显示样式。 2. **核心CSS属性** - 利用`:checked`伪类选择器检测是否选中状态,并触发相应的视觉变化。 - 设置过渡动画通过`transition`平滑切换开/关效果。 #### 示例代码 ```html <label class="switch"> <input type="checkbox" /> <span class="slider round"></span> </label> <style> .switch { position: relative; display: inline-block; width: 60px; /* 开关总宽度 */ height: 34px; /* 高度 */ } /* 隐藏原生输入框 */ .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; /* 默认背景色 */ transition: .4s; /* 动画时间 */ border-radius: 34px; /* 圆角矩形 */ } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; /* 滑块颜色 */ transition: .4s; /* 同步动画 */ border-radius: 50%; /* 完美圆形 */ } /* 当复选框被勾选时的状态 */ input:checked + .slider { background-color: #2196F3; /* 蓝色调表示“打开” */ } input:focus + .slider { box-shadow: 0 0 1px #2196F3; /* 焦点特效 */ } input:checked + .slider:before { transform: translateX(26px); /* 移动到右侧位置 */ } </style> ``` --- 上述代码展示了如何利用 CSS 的 `translateX()` 和伪元素 `before` 创建动态移动的效果。此外还包含了一些优化设计如焦点阴影、圆角等细节提升用户体验感。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值