【问题标题】:Target the parent div of a radio button when checked选中时定位单选按钮的父 div
【发布时间】:2014-06-14 01:10:58
【问题描述】:

我创建了方形而不是圆形的特殊单选按钮。我希望边框在它们被选中时在它们周围发生变化。它默认为白色,但我希望它变为黑色。我在使用“padder”类定位 div 时遇到问题。

HTML

<div class='specialRadio'>
    <div class='padder'><input class='red' type="radio" id="radio1" name="group"/><label class='' for="radio1"></label></div>
    <div class='padder'><input class='blue' type="radio" id="radio2" name="group"/><label class='' for="radio2"></label></div>
    <div class='padder'><input class='yellow' type="radio" id="radio3" name="group"/><label class='' for="radio3"></label></div>
</div>

CSS:

    .specialRadio input[type="radio"]{
        display:none;
    }

    .specialRadio input[type="radio"] + label
    {
        height: 16px;
        width: 16px; 
        display:inline-block;
        padding: 0 0 0 0px;
    }

    .padder{
        display:inline-block;
        padding: 2px;
        margin:2px; 
        border: 1px solid white;
    } 

    .red { background: red;}
    .blue  { background: blue;}
    .yellow  { background: yellow;}

这一行是我遇到问题的地方:

.specialRadio input[type="radio"]:checked>div{  /*select all parent divs where radio button is checked*/
    border:2px solid black;
}

我知道我可以执行以下 css 代码,但它针对的是标签的边框,而不是父 div。

.specialRadio input[type="radio"]:checked  + label{  
    border:2px solid black;
}

【问题讨论】:

标签: css


【解决方案1】:

你可以使用 jQuery:

$(".specialRadio input").change(function() { 
    if ($(this).is(":checked")) { 
        $(this).parent().siblings().css("border", "2px solid white");
        $(this).parent().css("border", "2px solid black"); 
    }
});

【讨论】:

  • 好主意,我什至没有考虑使用jquery。当涉及到逻辑时,jquery 总是比 css 好。我添加了一条线,使其他边框变回白色。 '$(".specialRadio input").change(function() { if ($(this).is(":checked")){ $(this).parent().siblings().css("border" , "2px 纯白"); $(this).parent().css("border", "2px 纯黑"); } });'
  • 将其添加到您的代码中,我会给您打勾。
  • 你去;尽管我认为您可以使用 $(this).css() 而不是 $(this).parent().siblings(),除非您要更改多个单选按钮,在这种情况下没问题。
【解决方案2】:

一些 javascript 将帮助您做到这一点。没有 css 可以完成这项工作。试试这个:

$('.specialRadio input').on('click', function() {
  if($(this).is(':checked') {
    $(this).parent('.padder').css({ borderColor: 'black' })
  } else {
    $(this).parent('.padder').css({ borderColor: 'white' })
  }
});

这个我没测试过,但是原理很重要。

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    相关资源
    最近更新 更多