コピペで簡単!CSSとjQueryでラジオボタンを装飾する

デフォルトのラジオボタンは見栄えが…
ってときには装飾してしまえばいいのだ
ってことでCSSとjQueryで装飾してみる。

HTML

  1. <label class="fed-radio fed-flxMid selected">
  2. <i class="fed-icRadio"></i>
  3. <span>テストラジオ①</span>
  4. <input type="radio" name="test" class="fed-inputRadio fed-hide" value="0" checked="true">
  5. </label>
  6. <label class="fed-radio fed-flxMid">
  7. <i class="fed-icRadio"></i>
  8. <span>テストラジオ②</span>
  9. <input type="radio" name="test" class="fed-inputRadio fed-hide" value="1">
  10. </label>

CSS

  1. .fed-flxMid {
  2. display: -webkit-flex;
  3. display: flex;
  4. -webkit-flex-wrap: wrap;
  5. flex-wrap: wrap;
  6. -webkit-align-items: center;
  7. align-items: center;
  8. }
  9. .fed-icRadio {
  10. position: relative;
  11. width: 20px;
  12. height: 20px;
  13. margin-right: 0.5em;
  14. background-color: #fff;
  15. border-radius: 100%;
  16. border: 1px solid #ccc;
  17. box-sizing: border-box;
  18. }
  19. .fed-icRadio::before {
  20. content: '';
  21. position: absolute;
  22. top: 4px;
  23. left: 4px;
  24. width: 10px;
  25. height: 10px;
  26. border-radius: 100%;
  27. background-color: #ccc;
  28. }
  29. .selected .fed-icRadio {
  30. border-color: #2e9afe;
  31. }
  32. .selected > .fed-icRadio::before {
  33. background-color: #2e9afe;
  34. }
  35. .fed-hide {
  36. display: none;
  37. }

jQuery

  1. <script>
  2. // ラジオボタンON/OFF inputの状態に順ずる
  3. function radioBtnChange(s){
  4. $('body').on('change',s,function(e){
  5. $('[name="'+e.currentTarget.name+'"]').each(function(i,k){
  6. if(k.checked){
  7. $(k).closest('label').addClass('selected');
  8. }else{
  9. $(k).closest('label').removeClass('selected');
  10. }
  11. });
  12. });
  13. }
  14. $(function(){
  15. // ラジオON/OFF
  16. radioBtnChange('.fed-inputRadio');
  17. });
  18. </script>

まとめ

仕組みはたったこれだけ、CSSを変更すればどんな表示も思いのまま!?
ぜひ使って見てください^^