jQuery 将单选按钮样式化为正方形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24516958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:34:12  来源:igfitidea点击:

Styling radio buttons into a square

jquerycss

提问by Rob M

I was given a design with square radio buttons.

我得到了一个带有方形单选按钮的设计。

Is there a way to style radio buttons to look like this?

有没有办法让单选按钮看起来像这样?

The only way, I think I could accomplish this is by using images, and swap the checked/checked state via an $.on('click')method.

我认为我可以完成的唯一方法是使用图像,并通过一种$.on('click')方法交换选中/选中状态。

采纳答案by agconti

You dont need to style a radio button. Just use a div:

您不需要设置单选按钮的样式。只需使用一个div:

Example in a fiddle: http://jsfiddle.net/kLGf4/2/

小提琴示例:http: //jsfiddle.net/kLGf4/2/

html:

html:

 <section>
    <header>
         <h1>Perfered Method of Contact</h1>

    </header>
    <div> <span>Choice 1</span>

        <div class="square-radio square-radio--clicked">
             <div class="square-radio--content"></div>
        </div>
    </div>
    <div> <span>Choice 2</span>

        <div class="square-radio">
            <div class="square-radio--content"></div>
        </div>
    </div>
</section>

css:

css:

.square-radio {
    border: 1px solid black;
    margin: 2px;
    width: 40px;
    height: 40px;
    position: relative;

}
.square-radio--clicked .square-radio--content{
    margin: auto;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: black;
    width: 20px;
    height: 20px;
}

js:

js:

$(document).ready(function () {
    $(document).on("click", ".square-radio", function () {
        $(this).toggleClass("square-radio--clicked");
    });
});

回答by Jacob Gray

This can be done quite easily with only CSS, no need for JS. The basic concept is to style an element that is a sibling of the input, creating a "fake" radio button:

这可以很容易地只用 CSS 来完成,不需要 JS。基本概念是为输入的兄弟元素设置样式,创建一个“假”单选按钮:

/* 
 * Hide the inputs. 
 */

input {
  display: none;
}


/*
 * Then, style the label so it looks like however you want.
 * Here's a quick rundown of how I did it here:
 */


/*
 * Some basic positioning styles, and we give it the pointer cursor to show 
 * that it's clickable
 */

label {
  display: inline-block;
  padding: 5px 10px;
  cursor: pointer;
}


/*
 * With how I decided to build this, the position: relative is super important.
 * We're going to position a pseudo element within this element(As it is the containing box)
 */

label span {
  position: relative;
  line-height: 22px;
}


/* 
 * Because we're using pseudo elements, a content property is required to make them appear.
 */

label span:before,
label span:after {
  content: '';
}


/*
 * We are using the :before peudo elemnt as the actual button,
 * then we'll position the :after over it. You could also use a background-image,
 * font-icon, or really anything if you want different styles.
 * For the specific style we're going for, this approach is simply the easiest, but
 * once you understand the concept you can really do it however you like.
 */

label span:before {
  border: 1px solid #222021;
  width: 20px;
  height: 20px;
  margin-right: 10px;
  display: inline-block;
  vertical-align: top;
}

label span:after {
  background: #222021;
  width: 14px;
  height: 14px;
  position: absolute;
  top: 2px;
  left: 4px;
  transition: 300ms;
  opacity: 0;
}

/*
 * This is the most important part of this whole file, if you understand what's happening here
 * you can really make this in so many different ways.
 * 
 * We start by selecting the input inside of the label, with "label input". From there we use the 
 * ":checked" selector to *only* select the input when it is checked. We then use the immediate sibling 
 * selector(+) to select the span, and then it's pseudo element :after(What we are using to mark the button)
 * Because we already styled the :after, all we have to do is set the opacity to 1, making it fade in.
 */
label input:checked+span:after {
  opacity: 1;
}


/* 
 * A little styling for the demo 
 */

body {
  background: #fbfbfb;
  font-family: Arial;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.7);
}
<label>
  <input type="radio" name="radio">
  <span>EMAIL</span>
</label>

<label>
  <input type="radio" name="radio">
  <span>PHONE</span>
</label>

Check the code comments for a more in-depth explanation, but here's the basics:

检查代码注释以获得更深入的解释,但这里是基础知识:



Start by creating a <label>as the wrapper. We use a label because events triggered on it will also be triggered on the associated input:

首先创建一个<label>作为包装器。我们使用标签是因为在其上触发的事件也将在关联的输入上触发:

<label></label>

Add a input to it:

给它添加一个输入:

<label>
    <input type="radio" name="demo">
</label>

Remember that radio buttons have to have the same name to be grouped. Now we throw a <span>after the input, so we have something to target in our CSS.

请记住,单选按钮必须具有相同的名称才能分组。现在我们<span>在输入之后抛出一个,所以我们在我们的 CSS 中有一些目标。

<label>
    <input type="radio" name="demo">
    <span></span>
</label>

And the HTML is all set. Check the CSS for the explanation there, it'll be easier to understand.

HTML 已经全部设置好了。检查 CSS 那里的解释,它会更容易理解。

回答by Jeremy S.

Here is the simplest I know of, a pure CSS solution requiring no labels or scripting. A couple of vendor prefixes are required for full compatibility:

这是我所知道的最简单的,一个不需要标签或脚本的纯 CSS 解决方案。完全兼容需要几个供应商前缀:

input[type='radio'] {
  box-sizing: border-box;
  appearance: none;
  background: white;
  outline: 2px solid #333;
  border: 3px solid white;
  width: 16px;
  height: 16px;
}

input[type='radio']:checked {
  background: #333;
}

As noted above, the box-sizingand appearanceproperties should be vendor-prefixed:

如上所述,box-sizingappearance属性应以供应商为前缀:

-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

回答by Jignesh Gohel

While searching for implementing squared radio buttons in context of Bootstrap I ended up finding this SO post.

在 Bootstrap 的上下文中搜索实现平方单选按钮时,我最终找到了这篇 SO 帖子。

Also I found other resources on web majority of which were based on Pure CSS. Most of the answers in this post too are based on Pure CSS.

我还在网络上发现了其他资源,其中大部分是基于纯 CSS 的。这篇文章中的大部分答案也是基于纯 CSS。

As a non-CSS developer the Pure CSS solutions, involving pseudo elements, I have found them to be lengthy and puzzling too. Puzzling because I could not figure out how the solution worked, by inspecting styling into the Developer's Tool on browsers.

作为一名非 CSS 开发人员,Pure CSS 解决方案涉及伪元素,我发现它们也很冗长且令人费解。令人困惑,因为我无法通过在浏览器上检查开发人员工具的样式来弄清楚解决方案是如何工作的。

Thus I preferred JS-based solution and @agconti's answer https://stackoverflow.com/a/24517110/936494helped in deriving it. Below I am posting my working solution

因此,我更喜欢基于 JS 的解决方案,@agconti 的回答https://stackoverflow.com/a/24517110/936494有助于推导出它。下面我发布了我的工作解决方案

Environment

环境

  • Bootstrap 3.x
  • jQuery 1.12.4
  • Font Awesome Icons
  • 引导程序 3.x
  • jQuery 1.12.4
  • 字体真棒图标

HTML

HTML

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-offset-1 col-md-10 square-radios-container">
            <div>
                <div class="square-radio">
                    <div class="square-radio-content"><i class="fa fa-check fa-fw"></i></div>
                </div>
                <span class="square-radio-label">Option 1</span></div>
            <br />
            <div>
                <div class="square-radio">
                    <div class="square-radio-content"><i class="fa fa-check fa-fw"></i></div>
                </div>
                <span class="square-radio-label">Option 2</span></div>
        </div>
    </div>
</div>

CSS

CSS

  .square-radio {
    border: 2px solid #ccc;
    border-radius: 4px;
    width: 1.25em;
    height: 1.25em;
    float: left;

    .square-radio-content {
      display: none;
      margin-top: -8px;
      margin-left: -2px;
      color: #00CDFF;
      font-size: 18px;
    }
  }

  .square-radio-label {
    margin-left: 6px;
    font-weight: bold;
  }

JS

JS

(function ($) {

  bindClickEventOnSquareRadios = function() {
    var squareRadios = $('.square-radios-container').find('.square-radio');

    squareRadios.off('click').on('click', function(event) {
      var squareRadioObj = $(this);

      // Reset radio selection for all radios except the one clicked.
      var squareRadiosContainerObj = squareRadioObj.closest('.square-radios-container');
      var presentlyCheckedRadio = squareRadiosContainerObj.find('.square-radio-clicked').find('.square-radio-content').hide();
      presentlyCheckedRadio.find('.square-radio-content').hide();
      presentlyCheckedRadio.removeClass('square-radio-clicked');

      // Show the clicked radio as checked
      squareRadioObj.addClass('square-radio-clicked');
      squareRadioObj.find('.square-radio-content').show();
    });
  };

}) (jQuery);

$(document).ready(function(){
    bindClickEventOnSquareRadios();
});

The rendered output looks like

渲染的输出看起来像

enter image description here

enter image description here

Hope this helps someone who prefer JS-based solution for the requirement.

希望这可以帮助那些喜欢基于 JS 的解决方案来满足需求的人。

Note: The styling should need to be tweaked to match the desired preference.

注意:应该需要调整样式以匹配所需的首选项。

回答by John S.

input[type=radio] {
  padding: 0.5em;
  -webkit-appearance: none;
  outline: 0.1em solid black;
  outline-offset: 0.1em;
}

input[type=radio]:checked {
  display: inline-block;
  background-color: #000;
}
<label for="radioA"><input type="radio" name="radio1" value="A"/> A</label><br>
<label for="radioB"><input type="radio" name="radio1" value="B"/> B</label><br>
<label for="radioC"><input type="radio" name="radio1" value="C"/> C</label><br>
<label for="radioD"><input type="radio" name="radio1" value="D"/> D</label>

example

example

回答by Travis L

try this:

尝试这个:

HTML:

HTML:

<label class="active">
    Email
    <span></span>
    <input type="radio" name="n1" value="email" checked />
</label>
<label>
    Phone
    <span></span>
    <input type="radio" name="n1" value="phone" />
</label>

CSS:

CSS:

label {
  width: 125px;
  display: block;
  float: left;
}
label input {
  display: none;
}
label span {
  display: block;
  width: 17px;
  height: 17px;
  border: 1px solid black;
  float: left;
  margin: 0 5px 0 0;
  position: relative;
}
label.active span:after {
  content: " ";
  position: absolute;
  left: 3px;
  right: 3px;
  top: 3px;
  bottom: 3px;
  background: black;
}

JS (requires jquery):

JS(需要jquery):

$(document).ready(function () {
    $('label').click(function() {
        $('.active').removeClass("active");
        $(this).addClass("active");
    });
});

Here is a fiddle where you can see it in action: http://jsfiddle.net/wqdHE/2/

这是一个小提琴,您可以在其中看到它的实际效果:http: //jsfiddle.net/wqdHE/2/