自定义单选框radio样式

时间:2022-12-08 10:40:26
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>自定义单选框radio样式</title>
</head>
<style>
body { margin: 0; }
input { padding: 0; margin: 0; border: 0; }
.female, .male { position: relative; /* 设置为相对定位,以便让子元素能绝对定位 */ height: 40px; line-height: 40px; margin-left: 40px; }
.sex label { display: block; height: 40px; width: 40px; line-height: 40px; font-size: 20px; cursor: pointer; }
.sex input { z-index: 3; position: absolute; top: 0; bottom: 0; left: 40px; margin: auto; /* 这里及以上的定位,可以让该元素竖直居中。(top: 0; bottom: 0;) */ opacity: 0; display: block; width: 30px; height: 30px; cursor: pointer; }
.sex span { position: absolute; top: 0; bottom: 0; left: 40px; margin: auto; display: block; width: 25px; height: 25px; border: 1px solid #000; border-radius: 50%; cursor: pointer; }
.sex span.active { background-color: #000;padding:-5px; }
</style>
<body>
<form action="">
<div class="sex">
<div class="female">
<label for="female">女</label>
<input type="radio" name="sex" id="female">
<span class="female-custom"></span> </div>
<div class="male">
<label for="male">男</label>
<input type="radio" name="sex" id="male">
<span class="male-custom"></span> </div>
</div>
</form>
<script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
$("#male").click( function () {
$(this).siblings("span").addClass("active");
$(this).parents("div").siblings("div").children("span").removeClass("active");
});
$("#female").click( function () {
$(this).siblings("span").addClass("active");
$(this).parents("div").siblings("div").children("span").removeClass("active");
});
</script>
</body>
</html>