单击时如何更改单选按钮的CSS

how to change css of radio button when clicked

本文关键字:CSS 单选按钮 何更改 单击      更新时间:2023-09-26
<style type="text/css">
.radiostyle {
    background-color: #999;
}
</style>
<label for="a1" class="radiostyle">
<Input type = radio Name = 1 Value = 100 Onclick="changecss()" id="a1">
100 bucks</label>

函数 changecss(( 的代码是什么,这样当单击单选按钮时,收音机背景会更改为其他颜色,例如绿色。请帮忙,我已经在网上找了几个小时没有解决方案。

您可以使用仅CSS解决方案(CSS3(:

.HTML:

<input type="radio" name="1" value="100" id="a1">
<label for="a1" class="radiostyle">100 bucks</label>

.CSS:

.radiostyle {
    background-color: #999;
}
input[type=radio]:checked+label {
/* Or `#a1:checked+label` if you only want it for that input */
    background-color: red;
}

http://jsfiddle.net/peSJG/

下面是一个快速的jQuery示例,说明如何做到这一点:

http://jsfiddle.net/NuzpR/

function changecss() {
    var rb = document.getElementsByClassName('radiostyle');
    rb[0].style.backgroundColor = 'red';
}​

js小提琴示例

如果你使用的是Jquery,你可以这样做:

$("#a1").click(changecss);
function changecss()
{
 $(this).parent().removeClass("radiostyle").addClass("selectedStyle");
}​

对于直接的javascript,其中selectedStyle定义了你的风格:

function changecss()
{
    this.parentNode.setAttribute("class", "selectedStyle");
}

这应该对你有所帮助。

  • 你必须使用 id 属性
  • 使用 getElementById() 获取该元素
  • 现在更改您喜欢的属性

.radiostyle { 背景颜色:#999; } .radiostyle1 { 背景颜色:#ffff; }

<script type="text/javascript">
    function changecss()
    {
        var e= document.getElementById("a1");
        e.className="radiostyle1";
    }
</script>

 <label for="a1" id="a1" class="radiostyle">
    <Input type ="radio" id="r1" Name ="r1" Value = 100 Onclick="changecss()" id="a1">
    100 bucks
</label>