页面需要一个选择性别的单选按钮,要求默认是根据后台返回值来选择“男”或“女”,然后可以手动进行修改。注:下图中单选按钮的按钮是图片,根据是否被选中来显示不同的图片。
先写出性别里的两个单选按钮。
<div class="userBox">
<div class="nameString">性别</div>
<input type="radio" name="sex" class="radio" id="male" value="男"/><label for="male" id="sexMale">男</label>
<input type="radio" name="sex" class="radio" id="female" value="女"/><label for="female" id="sexFemale">女</label>
</div>
然后进行判断,给定一个默认选中
if(this.usersex==="男")
document.getElementById("male").checked = true;
else if(this.usersex==="女")
document.getElementById("female").checked = true;
如果默认选择是“男”的话可以直接这样
document.getElementById("male").checked = true;
最后就是获取用户最后到底选了哪一个
let sexvalue=document.getElementsByName("sex")
let sex=""
for(let i=0;i<sexvalue.length;i++){
if(sexvalue[i].checked==true){
sex=sexvalue[i].value
}
}
就是把sex都获取出来,然后检查一下checked的状态,就可以得到选择了什么性别。
最最后补下前面说的单选按钮是根据是否被选择来选取不同图片的问题
.radio:checked{
position: absolute;
font-size: 28px;
color: #3A3D50;
background-size: cover;
background-image: url("../assets/selectedradio.png");
appearance: none;
-webkit-appearance: none;
outline: none;
width: 28px;
height: 28px;
}
.radio{
position: absolute;
font-size: 28px;
background-size: cover;
background-image: url("../assets/unselecedradio.png");
appearance: none;
-webkit-appearance: none;
outline: none;
width: 28px;
height: 28px;
background-color: #FFFFFF;
}