将单选按钮更改为图像 - 请稍微帮助一下?

时间:2012-10-08 02:19:27

标签: javascript css

我正在尝试将此页面上的单选按钮更改为图像
http://www.pazzle.co.uk/index.php?main_page=product_info&cPath=6_1&products_id=3

我正在使用本教程来完成它:
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

这个脚本似乎不适合我,是否有更好的解决方案可以将单选按钮更改为图像?

1 个答案:

答案 0 :(得分:2)

该教程很老,没有键盘支持,脚本看起来相当复杂......试试这个jQuery插件jq-customRadioCheck

你需要一个像这样的图像精灵:http://i.imgur.com/KSNpJ.png

<强> HTML:

<label><input type="checkbox"/>Checkbox</label>
<label><input type="radio"/>Radio</label>

<强> jQuery的:

;(function(){
$.fn.customRadioCheck = function() {

  return this.each(function() {

    var $this = $(this);
    var $span = $('<span/>');

    $span.addClass('custom-'+ ($this.is(':checkbox') ? 'check' : 'radio'));
    $this.is(':checked') && $span.addClass('checked'); // init
    $span.insertAfter($this);

    $this.parent('label').addClass('custom-label')
      .attr('onclick', ''); // Fix clicking label in iOS
    // hide by shifting left
    $this.css({ position: 'absolute', left: '-9999px' });

    // Events
    $this.on({
      change: function() {
        if ($this.is(':radio')) {
          $this.parent().siblings('label')
            .find('.custom-radio').removeClass('checked');
        }
        $span.toggleClass('checked', $this.is(':checked'));
      },
      focus: function() { $span.addClass('focus'); },
      blur: function() { $span.removeClass('focus'); }
    });
  });
};
}());

<强> CSS:

.custom-label {
  display: inline-block;
  margin-right: .8em;
  cursor: pointer;
}
.custom-radio,
.custom-check {
    vertical-align: middle;
    display: inline-block;
    position: relative;
    top: -.15em; /* Adjust to for best fit */
    margin: 0 .4em;
    width: 20px;
    height: 20px;
    background: url(customRadioCheck.png) 0 0 no-repeat;
}
.custom-radio { background-position: 0 -20px; }
.custom-check.focus { background-position: -20px 0; }
.custom-radio.focus { background-position: -20px -20px; }
.custom-check.checked { background-position: -40px 0; }
.custom-radio.checked { background-position: -40px -20px; }
.custom-check.checked.focus { background-position: -60px 0; }
.custom-radio.checked.focus { background-position: -60px -20px; }

演示: http://jsfiddle.net/elclanrs/BQp2F/