Html修改radio单选框样式,通过js绑定label与input关系,不使用id


前言

在使用表单元素单选框的时候,根据需求可能需要修改默认的单选框样式


效果图

在这里插入图片描述

一、样式改动思路

隐藏掉单选框input的默认样式,然后在label前面加上自定义的伪元素

二、通过js绑定label和input关系

input单选框选中是标签属性checked控制的,通过DOM操作,改变元素的checked属性值,做到绑定的效果

三、完整代码

<!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>
		div>input {
			display: none;
		}

		div>label {
			position: relative;
			margin-right: 34px;
		}

		div>label::before {
			display: inline-block;
			content: "";
			width: 16px;
			height: 16px;
			border-radius: 50%;
			border: 1px solid rgb(219, 219, 219);
			margin-right: 6px;
			vertical-align: bottom;
		}

		div>input:checked+label::before {
			background-color: rgb(239, 66, 56);
		}

		div>input:checked+label::after {
			display: inline-block;
			content: "";
			width: 6px;
			height: 6px;
			border-radius: 50%;
			position: absolute;
			left: 6px;
			bottom: 6px;
			background-color: white;
		}
	</style>
</head>

<body>
	<div>
		<div class="radiobox" onclick="label(event)">
			<input type="radio" name="paixu" checked />
			<label style="cursor: pointer" @click="点击">按热门排序</label> 
		</div>
		<div class="radiobox" onclick="label(event)">
			<input type="radio" name="paixu" /> 
			<label style="cursor: pointer">按评价排序</label> 
		</div>
		<div class="radiobox" onclick="label(event)">
			<input type="radio" name="paixu"  /> 
			<label style="cursor: pointer">按时间排序</label> 
		</div>
	</div>
</body>
<script type="text/javascript">
	function label(e) {
		if (e.target.tagName === "LABEL") {
			const arr = document.querySelectorAll("input");
			arr.forEach((item) => {
				item.checked = false;
			});
			e.target.previousElementSibling.checked = true;
			console.log(e.target.previousElementSibling, "555");
		}
		if (e.target.tagName === "INPUT") { }
		console.log(e);
		console.log(e.target);
	}
</script>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值