纯css实现switch开关

本文介绍了如何使用HTML、CSS和JavaScript创建一个简单的开关组件,当用户点击时,通过CSS和JavaScript控制其样式状态的变化,实现选中和取消选中的交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码比较简单,有需要直接在下边粘贴使用吧~

html:

	<div class="switch-box">
		<input id="switch" type="checkbox">
		<label></label>
	</div>

 css:

		.switch-box {
			position: relative;
			height: 25px;
		}

		.switch-box label {
			width: 50px;
			height: 25px;
			background: #ccc;
			position: relative;
			display: inline-block;
			border-radius: 46px;
			-webkit-transition: 0.4s;
			transition: 0.4s;
		}

		.switch-box label:after {
			content: '';
			position: absolute;
			width: 21px;
			height: 25px;
			border-radius: 100%;
			left: 0;
			top: -5px;
			z-index: 2;
			background: #fff;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
			-webkit-transition: 0.4s;
			transition: 0.4s;
		}

		.switch-box input {
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: 5;
			opacity: 0;
		}

		.switch-box label:after {
			top: 0;
			width: 23px;
			height: 23px;
			margin: 1px 0;
		}

		.switch-box input:checked+label {
			background: #eb8597;
		}

		.switch-box input:checked+label:after {
			left: 30px;
		}

js:

  $('#switch').change(function (e) {

      var isChecked = $(this).prop("checked") ? true : false;
		if (isChecked) {
			    console.log('选中...')
			} else {
			    console.log('取消选中...')
			}
	});

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值