动态添加删除class名

该博客展示了如何使用HTML和CSS创建一个具有两种选项(男/女)的性别选择框,并通过JavaScript实现点击切换选中状态的功能。示例代码包括了样式设计和事件监听,使得按钮在被点击时能够高亮显示选中状态。

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

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		.redioBox {
			width: 120px;
			height: 30px;
			margin: auto;
			display: flex;
			justify-content: space-between;
			border-radius: 20px;
			background-color: #f5f5f5;
		}

		.redioBtn {
			width: 50%;
			height: 100%;
			border-radius: 20px;
			display: flex;
			justify-content: center;
			align-items: center;
			cursor: pointer;
			overflow: hidden;
		}

		.redioBtnChen {
			background-color: rgb(15, 57, 245);
			color: #fff;
		}

		.redioBtn p {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	</style>
</head>

<body>
	<div class="redioBox">
		<div class="redioBtn">
			<p id="man">男</p>
		</div>
		<div class="redioBtn">
			<p id="woman">女</p>
		</div>
	</div>
</body>

</html>
<script>
	//添加类名:document.getElementById("myDiv").classList.add('mystyle');
	//删除类名:document.getElementById("myDiv").classList.remove('mystyle');

	let $ = (str) => {
		return document.querySelector(str);
	}
	let redionFun = () => {
		$('#woman').classList.add('redioBtnChen');
		$('#man').onclick = () => {
			$('#man').classList.add('redioBtnChen');
			$('#woman').classList.remove('redioBtnChen');
		}

		$('#woman').onclick = () => {
			$('#woman').classList.add('redioBtnChen');
			$('#man').classList.remove('redioBtnChen');
		}
	}
	redionFun();
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值