您好,欢迎访问一九零五行业门户网

JS怎样操作改变radio的状态

这次给大家带来js怎样操作改变radio的状态,js操作改变radio的状态的注意事项有哪些,下面就是实战案例,一起来看一下。
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。
效果如下:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
怎样实现微信web端后退强制刷新
react native使用fetch上传图片
用js快速的获取html页面中图片的地址
以上就是js怎样操作改变radio的状态的详细内容。
其它类似信息

推荐信息