【问题标题】:how to change css of radio button when clicked [closed]单击时如何更改单选按钮的CSS [关闭]
【发布时间】:2012-09-10 22:48:10
【问题描述】:
<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() 的代码是什么,以便在单击单选按钮时,单选背景更改为其他颜色,例如绿色。请帮忙,我在网上找了几个小时都没有解决方案。

【问题讨论】:

  • 您对 jQuery 解决方案满意还是必须是纯 javascript?
  • 您是如何搜索了几个小时却没有找到解决方案的? xahlee.info/js/css_change.html(第一个谷歌结果)stackoverflow.com/questions/195951/…
  • 问了很多次,很容易用谷歌搜索。此外,还有一个 :checked: CSS3 伪类,无需 javascript 即可工作。
  • 欢迎来到 Stack Overflow!我们希望您尝试自己解决此问题,而不是要求社区为您提供完整的解决方案。当您有一些代码向我们展示证明您所做的一些努力时(即使它是错误的),请更新您的问题并标记以重新打开。谢谢。

标签: javascript html css onclick


【解决方案1】:

您可以使用纯 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/

【讨论】:

【解决方案2】:

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

http://jsfiddle.net/NuzpR/

【讨论】:

    【解决方案3】:
    function changecss() {
        var rb = document.getElementsByClassName('radiostyle');
        rb[0].style.backgroundColor = 'red';
    }​
    

    jsFiddle example

    【讨论】:

      【解决方案4】:

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

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

      对于直接 javascript,其中 selectedStyle 定义了您的样式:

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

      【讨论】:

        【解决方案5】:

        这应该对你有帮助..

        • 你必须使用 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>
        

        【讨论】:

          猜你喜欢
          • 2012-09-08
          • 1970-01-01
          • 2018-10-15
          • 1970-01-01
          • 1970-01-01
          • 2015-08-16
          • 2019-05-09
          • 2014-06-03
          • 1970-01-01
          相关资源
          最近更新 更多