如何在Bootstrap中设置单选按钮的样式?

时间:2017-12-29 13:02:19

标签: javascript css twitter-bootstrap

我不允许使用jquery。只有JavaScript,CSS和Bootstrap。

如何更改单选按钮的默认外观?

WHAT I HAVE

WHAT I WANT

到目前为止,这是我的代码。

"的test.html"

            <div class="radio">
            <label><input type="radio" name="optradio" id="radA" onclick="storeA()">
              <p id="optionA"></p><br>
            </label>
          </div>
          <div class="radio">
            <label><input type="radio" name="optradio" id="radB" onclick="storeB()">
              <p id="optionB"></p><br>
            </label>
          </div>
          <div class="radio">
            <label><input type="radio" name="optradio" id="radC" onclick="storeC()">
              <p id="optionC"></p><br></label>
          </div>
          <div class="radio">
            <label><input type="radio" name="optradio" id="radD" onclick="storeD()">
              <p id="optionD"></p><br></label>
          </div>
          <div class="radio">
            <label><input type="radio" name="optradio" id="radE" onclick="storeE()">
              <p id="optionE"></p><br></label>
          </div>

1 个答案:

答案 0 :(得分:2)

好的,我有一支笔给你。但是如果你想真正学习一些东西,请仔细阅读这些阅读评论。

要记住的要点:

  • 隐藏无线电
  • 生成新的单选按钮,我们可以通过伪元素通过css设置样式:在
  • 之后或之前
  • 使用伪选择器检查按钮时应用样式:选中

这里的完整工作代码---&gt; https://codepen.io/nikolamitic/pen/MrmYdM?editors=1100

 <div class="questions">
  <div class="questions__question">
    <input type="radio" name="answer" id="answer-1">
    <label for="answer-1" data-question-number="1">Car</label>
  </div>
  <div class="questions__question">
    <input type="radio" name="answer" id="answer-2"> 
    <label for="answer-2" data-question-number="2">Kralj</label>
  </div>
  <div class="questions__question">
    <input type="radio" name="answer" id="answer-3">
    <label for="answer-3" data-question-number="3">Faca</label>
  </div>
</div>

/* Using css var aka custom properies, don't use them if you don't use tools such as postCss */
:root {
  --color-blue: #5897fc;
  --color-blue-grayed: #e0ecff;
}
/* First hide radios */
.questions input[type="radio"] {
  display: none;
}

/* Generate new radio buttons, which we can style via css */
.questions label:before {
  content: attr(data-question-number);
  display: inline-block;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 1px solid;
  text-align: center;
  line-height: 30px;
  margin-right: 20px;
}

/* Applying styles when checking the buttons */
.questions input[type="radio"]:checked ~ label {
  background-color: var(--color-blue-grayed);
  border-color: var(--color-blue);
}

.questions input[type="radio"]:checked ~ label:before {
  background-color: var(--color-blue);
  border-color: var(--color-blue);
  color: white;
}

.questions label {
  display: block;
  cursor: pointer;

  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  border: 2px solid white;
  border-radius: 15px;
}

.questions {
  background-color: gray;
  padding: 20px;
}