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。
效果如下:
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
怎樣實現微信web端后退強制刷新
react native使用fetch上傳圖片
用js快速的獲取html頁面中圖片的地址
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com