简体   繁体   English

将CSS添加到单选按钮以选中并清除JS中未选中的CSS

[英]Adding css to radio button for checked and clear css unchecked in js

How do I style the radio button for checked only and clear it? 如何设置仅选中状态的单选按钮的样式并清除它? I've tried several ways. 我尝试了几种方法。 It's not clearing. 还没结算

$('input:radio').on('click', function () {
    var $field_type = $("[name=field]:checked");
    #and other field types doing the same thing
    $("label[for='" + $field_type.attr('id') + "']").css({'border': '2px solid #333'})

I also tried $("label[for='" + $(this).attr('id') + "']").css({'border': '2px solid #333'}) . 我还尝试了$("label[for='" + $(this).attr('id') + "']").css({'border': '2px solid #333'}) It does the same thing. 它做同样的事情。

 $('input:radio').on('click', function () { $('input[name="RD"]').next().css({'border': 'none'}); $("label[for='" + $(this).attr('id') + "']").css({'border': '2px solid #333'}) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="RD" id="RD1"/><label for="RD1">radio1</label> <br> <input type="radio" name="RD" id="RD2"/><label for="RD2">radio2</label> 

The best approach is to simply write a CSS selector that kicks in when the radio button is checked. 最好的方法是简单地编写一个CSS选择器,该选择器在选中单选按钮时会弹出。 No JavaScript needed. 无需JavaScript。

But keep in mind that not all browsers allow radio buttons to be styled in any way you like. 但是请记住,并非所有浏览器都允许以您喜欢的任何方式设置单选按钮的样式。 However, the label elements that go with them can be styled easily: 但是,可以轻松设置与之配套的标签元素的样式:

 /* This rule will only be appled when the radio button is selected. but, not all browsers allow radio button styling. */ input[type='radio']:checked { background-color:yellow; } /* This rule will affect the label that comes after the checked radio button: */ input[type='radio']:checked + label { border:1px solid red; } 
 <input type="radio" name="test" id="test" value="on"><label for="test">On</label> <input type="radio" name="test" id="test2" value="off"><label for="test2">Off</label> 

Here's an interesting link that shows how to customize the buttons and check marks easily. 这是一个有趣的链接 ,显示了如何轻松自定义按钮和复选标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM