jQuery实现自定义checkbox和radio样式


Posted in Javascript onJuly 13, 2015

1,起因

最近在工作中要实现自定义式的radio样式,而我们通常使用的时默认的样式,因为自己实在想不到解决的方法,于是开始搜索,最终看到了不错的解决办法,可以完美解决我们遇到的问题。

2,原理

大家都知道在写结构的时候,radio或checkbox都会跟随label一起使用,label的for属性值和input的id值相同的情况下,点击label就可以选中input,这里正是利用label 来覆盖我们的input默认样式,通过给label添加背景图片(美化的checkbox或radio),也就是在点击的过程中,我们是看不到默认的input的(给input设置z-index:-1),而点击的是label,通过不同的事件,加载不同的背景图片(这里是改变背景图片的位置)

3,设置美化checkbox或radio的默认样式

(1)页面结构

<form class="form" method="post">
  <fieldset>
    <legend>Which genres do you like?</legend>
    <input type="checkbox" value="action" id="check-1" name="genre"><label for="check-1" class="">Action / Adventure</label>
    <input type="checkbox" value="comedy" id="check-2" name="genre"><label for="check-2" class="">Comedy</label>
    <input type="checkbox" value="epic" id="check-3" name="genre"><label for="check-3" class="">Epic / Historical</label>
    <input type="checkbox" value="science" id="check-4" name="genre"><label for="check-4" class="">Science Fiction</label>
    <input type="checkbox" value="romance" id="check-5" name="genre"><label for="check-5" class="">Romance</label>
    <input type="checkbox" value="western" id="check-6" name="genre"><label for="check-6" class="">Western</label>
  </fieldset> 
  <fieldset>
    <legend>Caddyshack is the greatest movie of all time, right?</legend>
    <input type="radio" value="1" id="radio-1" name="opinions"><label for="radio-1" class="">Totally</label>
    <input type="radio" value="1" id="radio-2" name="opinions"><label for="radio-2" class="">You must be kidding</label>
    <input type="radio" value="1" id="radio-3" name="opinions"><label for="radio-3" class="">What's Caddyshack?</label>
  </fieldset>
</form>

 (2)jquery code(前提必须引入jquery库)

jQuery.fn.customInput = function(){
  $(this).each(function(i){
    if($(this).is('[type=checkbox],[type=radio]')){
      var input = $(this);
      //get the associated label using the input's id
      var label = $('label[for='+input.attr('id')+']');
      //get type,for classname suffix
      var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
      //wrap the input + label in a div
      $('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input,label);
      //find all inputs in this set using the shared name attribute
      var allInputs = $('input[name='+input.attr('name')+']');
      //necessary for browsers that don't support the :hover pseudo class on labels
      label.hover(function(){
        $(this).addClass('hover');
        if(inputType == 'checkbox' && input.is(':checked')) {
          $(this).addClass('checkedHover');
        }
      },function(){
        $(this).removeClass('hover checkedHover');
      });
       
      //bind custom event, trigger it, bind click,focus,blur events
      input.bind('updateState',function(){
        if(input.is(':checked')){
          if(input.is(':radio')){
            allInputs.each(function(){
              $('label[for='+$(this).attr('id')+']').removeClass('checked');
            });
          };
          label.addClass('checked');
        } else {
          label.removeClass('checked checkedHover checkedFocus');
        }
      })
      .trigger('updateState')
      .click(function(){
        $(this).trigger('updateState');
      })
      .focus(function(){
        label.addClass('focus');
        if(inputType == 'checkbox' && input.is(':checked')) {
          $(this).addClass('checkedFocus');
        }
      })
      .blur(function(){
        label.removeClass('focus checkedFocus');
      });        
    }
  });
}

 引入jquery库,再引入上面的代码后,就可以执行下面的代码

$('input').customInput();

 (3)生成的外层div

如果你的代码结构是label和input成对写的话,那么在它们的外层就会生成一个div,如图

jQuery实现自定义checkbox和radio样式

(4)设置自定义默认样式

准备好一张图,如下:

jQuery实现自定义checkbox和radio样式

你可能会问,为什么上面没有在顶端,而是有一定的距离,因为我们的input选项多是居中的,而我们是使用label的背景图片来模拟的,所以我们是为了让input选项居中显示。总之:ico小图标一定要垂直排列,一定要留有一定的距离来达到居中显示。

/* wrapper divs */
      .custom-checkbox,
      .custom-radio {
        position: relative;
        display: inline-block;
      }
      /* input, label positioning */
      .custom-checkbox input,
      .custom-radio input {
        position: absolute;
        left: 2px;
        top: 3px;
        margin: 0;
        z-index: -1;
      }
      .custom-checkbox label,
      .custom-radio label {
        display: block;
        position: relative;
        z-index: 1;
        font-size: 1.3em;
        padding-right: 1em;
        line-height: 1;
        padding: .5em 0 .5em 30px;
        margin: 0 0 .3em;
        cursor: pointer;
      }

 这是最外层的一些设置,当然你可以自己修改

/* ==默认状态效果== */
      .custom-checkbox label { 
        background: url(images/checkbox.gif) no-repeat; 
      }
      .custom-radio label { 
        background: url(images/button-radio.png) no-repeat; 
      }
      .custom-checkbox label, 
      .custom-radio label {
        background-position: 0px 0px;
      }
/*==鼠标悬停和得到焦点状态==*/
      .custom-checkbox label.hover,
      .custom-checkbox label.focus,
      .custom-radio label.hover,
      .custom-radio label.focus {
        /*background-position: -10px -114px;*/
      }
      
      /*==选中状态==*/
      .custom-checkbox label.checked,
      .custom-radio label.checked {
        background-position: 0px -47px;
      }
      .custom-checkbox label.checkedHover,
      .custom-checkbox label.checkedFocus {
        /*background-position: -10px -314px;*/
      }
      .custom-checkbox label.focus,
      .custom-radio label.focus {
        outline: 1px dotted #ccc;
      }

结尾:总之,我是完美的解决了我的问题,顺便截图发一个看看

jQuery实现自定义checkbox和radio样式

以上所述就是本文的全部内容了,希望大家能够喜欢。

Javascript 相关文章推荐
JavaScript+CSS控制打印格式示例介绍
Jan 07 Javascript
JS实现的网页倒计时数字时钟效果
Mar 02 Javascript
简介JavaScript中substring()方法的使用
Jun 06 Javascript
jQuery实现的数值范围range2dslider选取插件特效多款代码分享
Aug 27 Javascript
AngularJS+Node.js实现在线聊天室
Aug 28 Javascript
AngularJS入门心得之directive和controller通信过程
Jan 25 Javascript
js闭包引起的事件注册问题介绍
Mar 29 Javascript
BootStrap的弹出框(Popover)支持鼠标移到弹出层上弹窗层不隐藏的原因及解决办法
Apr 03 Javascript
js实现登录与注册界面
Nov 01 Javascript
vue 实现类似淘宝星级评分的示例
Mar 01 Javascript
Node.js API详解之 Error模块用法实例分析
May 14 Javascript
详解JavaScript中的数据类型,以及检测数据类型的方法
Sep 17 Javascript
javascript作用域问题实例分析
Jul 13 #Javascript
javascript中使用正则表达式清理table样式的代码
Apr 01 #Javascript
jquery实现图片上传之前预览的方法
Jul 11 #Javascript
JavaScript使用RegExp进行正则匹配的方法
Jul 11 #Javascript
javascript中JSON对象与JSON字符串相互转换实例
Jul 11 #Javascript
javascript实现下班倒计时效果的方法(可桌面通知)
Jul 10 #Javascript
JavaScript清空数组元素的两种方法简单比较
Jul 10 #Javascript
You might like
php中json_decode()和json_encode()的使用方法
2012/06/04 PHP
php轻松实现文件上传功能
2016/03/03 PHP
非常有用的9个PHP代码片段
2016/04/06 PHP
Yii2中设置与获取别名的函数(setAlias和getAlias)用法分析
2016/07/25 PHP
PHP的消息通信机制测试实例
2016/11/10 PHP
php+Ajax处理xml与json格式数据的方法示例
2019/03/04 PHP
动态控制Table的js代码
2007/03/07 Javascript
一个很简单的jquery+xml+ajax的无刷新树结构(无css,后台是c#)
2010/06/02 Javascript
js 获取和设置css3 属性值的实现方法
2013/05/06 Javascript
模仿password输入框的实现代码
2016/06/07 Javascript
用NodeJS实现批量查询地理位置的经纬度接口
2016/08/16 NodeJs
yarn的使用与升级Node.js的方法详解
2017/06/04 Javascript
前端图片懒加载(lazyload)的实现方法(提高用户体验)
2017/08/21 Javascript
jquery的 filter()方法使用教程
2018/03/22 jQuery
vue打包之后生成一个配置文件修改接口的方法
2018/12/09 Javascript
解决layui动态添加的元素click等事件触发不了的问题
2019/09/20 Javascript
[01:02:53]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第二局
2016/03/06 DOTA
python中的sort方法使用详解
2014/07/25 Python
实例探究Python以并发方式编写高性能端口扫描器的方法
2016/06/14 Python
快速排序的算法思想及Python版快速排序的实现示例
2016/07/02 Python
使用Python写一个量化股票提醒系统
2018/08/22 Python
python求最大值最小值方法总结
2019/06/25 Python
numpy求平均值的维度设定的例子
2019/08/24 Python
使用虚拟环境打包python为exe 文件的方法
2019/08/29 Python
Python如何读写CSV文件
2020/08/13 Python
通过HTML5 Canvas API绘制弧线和圆形的教程
2016/03/14 HTML / CSS
德国最大的网上鞋店之一:Schuhe24.de
2017/06/10 全球购物
澳大利亚百货商店中销量第一的商务衬衫品牌:Van Heusen
2018/07/26 全球购物
June Jacobs尊积帕官网:知名的spa水疗护肤品牌
2019/03/21 全球购物
先进集体获奖感言
2014/02/13 职场文书
大学生党员个人对照检查材料范文
2014/09/25 职场文书
手机被没收的检讨书
2014/10/04 职场文书
党员学习群众路线心得体会
2014/11/04 职场文书
《我们的民族小学》教学反思
2016/02/19 职场文书
2019最新婚庆对联集锦!
2019/07/10 职场文书
python 爬取吉首大学网站成绩单
2021/06/02 Python