怎么修改单选框radio默认样式

默认radio的样式为:
radio
怎么改为图片替代,并能获取选中的值

阅读 160.3k
5 个回答

苏生兄你标签选的 jQuery,那么我就用 jQuery 尝试实现下这个效果,因为 jQuery 学得不深,因此不一定是最佳方案,背景图直接从网上找到。:)
先把 HTML 码好:

<div>
  <input type="radio" id="nba" checked="checked" name="sport" value="nba">
  <label name="nba" class="checked" for="nba">NBA</label>
  <input type="radio" id="cba" name="sport" value="cba">
  <label name="cba" for="cba">CBA</label>
</div>

接着是 CSS:

input[type="radio"] {
  margin: 3px 3px 0px 5px;
  display: none;
}
label {
  padding-left: 20px;
  cursor: pointer;
  background: url(bg.gif) no-repeat left top;
}
label.checked {
  background-position: left bottom;
}

再就是 jQuery 代码了:

$(function() {
  $('label').click(function(){
    var radioId = $(this).attr('name');
    $('label').removeAttr('class') && $(this).attr('class', 'checked');
    $('input[type="radio"]').removeAttr('checked') && $('#' + radioId).attr('checked', 'checked');
  });
});

效果如下:

请输入图片描述

点击 CBA 后:

请输入图片描述

背景图 bg.gif 一并上传如下:

请输入图片描述

刚看到你的问题中还有一个取得选中的单选按钮的值,这个不难取得:

$('input[type="radio"]:checked').attr('value')

使用CSS3的写法

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
            <title>
                Document
            </title>
        </meta>
        <style media="screen" type="text/css">
            .button{
                padding: 5px 10px;
                background-color: #AEAEAE;
                cursor: pointer;
            }

            .radio > input[type=radio]:checked ~ .button{
                background-color: #4F4;
            }

            .radio > input[type=radio]{
                display: none;
            }
        </style>
    </head>
    <body>
        <label class="radio">
            <input name="r" type="radio" value="a"/>
            <span class="button">A</span>
        </label>
        <label class="radio">
            <input name="r" type="radio" value="b"/>
            <span class="button">B</span>
        </label>
    </body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏