Пользовательские флажки - PullRequest
       9

Пользовательские флажки

0 голосов
/ 12 ноября 2009

Я написал небольшой простой скрипт, который позволяет мне использовать пользовательские флажки. Он отлично работает в браузерах на базе FF, Opera и webkit, но, как обычно, IE вызывает у меня головную боль.

Поведение в IE действительно странное, похоже, что оно проверяет и снимает флажки случайных полей при каждом клике. Ну, может, это не так, но я действительно не вижу никакой последовательности.

Вы можете просмотреть код и протестировать его самостоятельно на http://i5.be/EX. Пример написан на HTML5, а также после того, как он протестирован в старом добром XHTML1.0, проблема, к сожалению, та же. Таким образом, проблема не связана с типом документа HTML5.

Есть идеи, как это исправить?

Cheers, Benjamin

Ответы [ 4 ]

1 голос
/ 12 ноября 2009

В качестве отправной точки я бы использовал событие click вместо события change. Попробуйте:

  $("body")
    .addClass(settings.bodyJsClass)
    .find(":checkbox")
    .filter("." + settings.customClass)
    .each(styleCheckStatus)
    .click(styleCheckStatus);
0 голосов
/ 30 июля 2015

Вот что вам поможет. Я потратил пару часов на их изготовление:

Радиокнопки:

window.onload = function() {
  var radioButtonGroups = document.getElementsByClassName('radioGroupContainer');
  for (var i = 0; i != radioButtonGroups.length; i++) {
    var radioButtons = radioButtonGroups[i].getElementsByClassName('radioButtonContainer');
    for (var i = 0; i != radioButtons.length; i++) {
      radioButtons[i].onclick = function() {
        var value = this.children[0].getAttribute('name');
        for (var i = 0; i != radioButtons.length; i++) {
          radioButtons[i].children[0].setAttribute('class', 'radioButtonDot');
        }
        this.children[0].setAttribute('class', 'radioButtonDotActive');
        this.parentNode.setAttribute('name', value);
      };
    }
  }
};
/*
* Created by William Green.
* Questions or comments? Email william.green@protonmail.com
* I would appreciate credit for this code if you use it; but it is not required.
* Last updated July 26, 2015
* Created July 26, 2015
*
*/

.radioButtonContainer {
  background-color: #eee;
  padding: 5px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  display: table;
  margin-top: 5px;
  margin-bottom: 5px;
}
.radioButtonContainer .radioButtonDot {
  width: 16px;
  height: 16px;
  background-color: transparent;
  border: 1px solid #000;
  display: inline-block;
  vertical-align: middle;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  -o-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -webkit-transition: all .5s ease;
  -ms-transition: all .5s ease;
  transition: all .5s ease;
}
.radioButtonContainer .radioButtonDotActive {
  width: 16px;
  height: 16px;
  background-color: #1396DE;
  border: 1px solid transparent;
  display: inline-block;
  vertical-align: middle;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  -o-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -webkit-transition: all .5s ease;
  -ms-transition: all .5s ease;
  transition: all .5s ease;
}
.radioButtonContainer .radioButtonLabel {
  background-color: transparent;
  display: inline-block;
  vertidal-align: middle;
  border: 0;
}
<div class="radioGroupContainer" id="radioChoicesOne">
  <div class="radioButtonContainer">
    <div class="radioButtonDot" name="optionOne"></div>
    <input type="button" class="radioButtonLabel" value="Option One">
  </div>
  <div class="radioButtonContainer">
    <div class="radioButtonDot" name="optionTwo"></div>
    <input type="button" class="radioButtonLabel" value="Option Two">
  </div>
  <div class="radioButtonContainer">
    <div class="radioButtonDot" name="optionThree"></div>
    <input type="button" class="radioButtonLabel" value="Option Three">
  </div>
</div>

<div id="radioButtonGroupOneValue"></div>
<input type="button" value="Get radio button value..." onclick="document.getElementById('radioButtonGroupOneValue').innerHTML = document.getElementById('radioChoicesOne').getAttribute('name');">

Флажки:

window.onload = function() {
  var checkboxes = document.getElementsByClassName('checkbox');
  for (var i = 0; i != checkboxes.length; i++) {
    if (checkboxes[i].hasAttribute('name') == false) {
      checkboxes[i].setAttribute('name', 'notChecked');
    } else {
      if (checkboxes[i].getAttribute('name') == 'checked') {
        checkboxes[i].setAttribute('name', 'checked');
        checkboxes[i].children[0].className = 'checkboxDotActive';
      }
    }

    checkboxes[i].onclick = function() {
      if (this.getAttribute('name') == 'checked') {
        this.setAttribute('name', 'notChecked');
        this.children[0].className = 'checkboxDot';
      } else {
        this.setAttribute('name', 'checked');
        this.children[0].className = 'checkboxDotActive';
      }
    };
  }
};
/*
* Questions or comments? Please email william.green@protonmail.com
* Credit for this project goes to William Green (me).
* Created July 25, 2015
* Last updated July 25, 2015
* I would like appropriate credit for this code, although it is not required.
*
* Thank you for looking, hope you find it useful.
* Please come back, since I may be adding more features to the code to allow for advanced functionality.
*
* PLEASE NOTE THAT THE 'checkboxDot' DIV MUST COME BEFORE ANY OTHER INNER MARKUP.
* IT MUST COME IMMEDIATELY AFTER THE PARENT DIV! IT WILL NOT WORK OTHERWISE!!!
*
* Thank you for showing interest in this code!
*/

/*IMPORTANT STYLES... THE STYLES LATER ARE NOT DIRECTLY RELATED THE THE CHECKBOXES*/

.checkbox {
  background-color: #eee;
  border-radius: 3px;
  padding: 5px;
  display: table;
}
.checkbox input {
  outline: none;
  border: 0;
  background-color: transparent;
  display: inline-block;
  vertical-align: middle;
}
.checkbox .checkboxDot {
  background-color: transparent;
  border: 1px solid #000;
  display: inline-block;
  vertical-align: middle;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  -o-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -webkit-transition: all .5s ease;
  -ms-transition: all .5s ease;
  transition: all .5s ease;
}
.checkbox .checkboxDotActive {
  background-color: #01A1DB;
  border: 1px solid transparent;
  display: inline-block;
  vertical-align: middle;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  -o-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -webkit-transition: all .5s ease;
  -ms-transition: all .5s ease;
  transition: all .5s ease;
}
/*END IMPORTANT STYLES*/

/*START IRRELEVANT STYLES*/

.valueButton {
  margin-top: 10px;
}
/*END IRRELEVANT STYLES*/
<h1>Javascript, html, and css checkboes -- best browser support ever!</h1>


<h3>Normal checkbox</h3>

<div id="checkboxOne" class="checkbox">
  <div class="checkboxDot"></div>
  <input type="button" value="Item 1">
</div>
<div id="checkboxOneStatus"></div>
<input type="button" class="valueButton" onclick="document.getElementById('checkboxOneStatus').innerHTML = document.getElementById('checkboxOne').getAttribute('name');" value="Is it checked?">

<h3>Checked by default</h3> 
<div id="checkboxTwo" class="checkbox" name="checked">
  <div class="checkboxDot"></div>
  <input type="button" value="Item 2">
</div>
<div id="checkboxTwoStatus"></div>
<input type="button" class="valueButton" onclick="document.getElementById('checkboxTwoStatus').innerHTML = document.getElementById('checkboxTwo').getAttribute('name');" value="Is it checked?">
0 голосов
/ 12 ноября 2009

Событие change для флажков вызывается только при двойном нажатии флажка. Так что, действительно, используйте событие click. Кстати, это касается и радио кнопок.

0 голосов
/ 12 ноября 2009

Это ошибка в событии IE6 onChange, когда она не срабатывает, пока флажок не потеряет фокус (в частности, когда срабатывает событие onBlur). Вы можете проверить это на своей странице, щелкнув по одному из полей, а затем щелкнув где-нибудь еще.

Одним из исправлений было бы присоединение всего события к label (Самое элегантное решение).

В качестве альтернативы, вы можете взять его в свои руки и выполнить события onClick и onBlur флажка вручную при нажатии на ярлык. Это ненавязчивое решение, и оно не должно требовать каких-либо изменений в существующем коде.

  $("label").click(function(e) {
    e.preventDefault();
    $("#" + $(this).attr("for")).click().blur();
  });

Не проверено, но вы поняли:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...