时间:2021-07-01 10:21:17 帮助过:258人阅读
h5的radio是自带选中状态改变的,但是如果自带的状态无法满足自己的需求时,就需要自己去实现。
代码如下:
h5部分代码
<p class="group"> <label class="active"> <input type="radio" name="parent_radio" value="1" id="new_data" onclick="change()"/> 最新资料</label> <label> <input type="radio" name="parent_radio" value="0" id="my_data" onclick="change()"/> 我的资料</label> <label> <input name="parent_radio" type="radio" id="screen_data" value="0" onclick="change()"/> 分类浏览</label> <label> <input type="radio" name="parent_radio" value="0" id="history_data" onclick="change()"/> 浏览历史</label> </p>
CSS代码
<style>
input[type="radio"] {
/*取消自带按钮*/
color:gray;
display: none;
}
.group>label:hover{
/*鼠标移到控件上做的改变*/
background-color: cornflowerblue;
}
.group>label{
/*未选中状态*/
float: left;
color: #4A4A4A;
font-size: 16px;
padding: 10px 11px;
}
.group>label.active{
/*选中状态*/
color: #316CEB;
font-size: 16px;
border-top: 2px solid #316CEB;
padding: 10px 11px;
}
</style>JS方法代码
<script type = "text/javascript">
function change()
{
var radio = document.getElementsByName("parent_radio");
/*用ByName是为了取到所有的radio*/
var radioLength = radio.length;
for(var i = 0;i < radioLength;i++)
{
if(radio[i].checked)
{
radio[i].parentNode.setAttribute('class', 'active');
}else {
radio[i].parentNode.setAttribute('class', '');
}
}
}
</script>效果如下

这里实现的是顶部boder的动态显示隐藏并且这里radio左侧默认的圆形按钮设为了隐藏。如果想要按钮不隐藏,需要作如下修改
<p class="group"> <label class="active"><img src="images/delate_choose.png" name="image"> <input type="radio" name="parent_radio" value="1" id="new_data" onclick="change()"/> 最新资料</label> <label> <img src="images/delate_no_choose.png" name="image"> <input type="radio" name="parent_radio" value="0" id="my_data" onclick="change()"/> 我的资料</label> <label> <img src="images/delate_no_choose.png" name="image"> <input name="parent_radio" type="radio" id="screen_data" value="0" onclick="change()"/> 分类浏览</label> <label> <img src="images/delate_no_choose.png" name="image"> <input type="radio" name="parent_radio" value="0" id="history_data" onclick="change()"/> 浏览历史</label> </p>
即在每一个raido类型的input前面加一个img(注意选中和未选中的区别),JS的change方法做以下修改
var radio = document.getElementsByName("parent_radio");
var img = document.getElementsByName("image");
/*用ByName是为了取到所有的radio*/
var radioLength = radio.length;
for(var i = 0;i < radioLength;i++)
{
if(radio[i].checked)
{
img[i].src = "images/delate_choose.png";
radio[i].parentNode.setAttribute('class', 'active');
}else {
img[i].src = "images/delate_no_choose.png";
radio[i].parentNode.setAttribute('class', '');
}
}img的length肯定和radio的length一样,所以可以只取一个length。
效果如下:

上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
如何使用Vue-Router模式和钩子(详细教程)
在vue-cli中使用vue-router搭建底部导航栏(详细教程)
在AngularJS中使用select加载数据选中默认值的方法该怎么处理?
以上就是如何通过js实现动态改变radio状态(详细教程)的详细内容,更多请关注Gxl网其它相关文章!