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 相关文章推荐
判断脚本加载是否完成的方法
May 26 Javascript
由JavaScript技术实现的web小游戏(不含网游)
Jun 12 Javascript
jQuery学习总结之元素的相对定位和选择器(持续更新)
Apr 26 Javascript
jquery Mobile入门—外部链接切换示例代码
Jan 08 Javascript
用html5 js实现点击一个按钮达到浏览器全屏效果
May 28 Javascript
JavaScript事件委托技术实例分析
Feb 06 Javascript
EasyUI在Panel上动态添加LinkButton按钮
Aug 11 Javascript
javaScript手机号码校验工具类PhoneUtils详解
Dec 08 Javascript
Vue2.0子同级组件之间数据交互方法
Feb 28 Javascript
vue项目部署到nginx/tomcat服务器的实现
Aug 26 Javascript
jQuery实现轮播图源码
Oct 23 jQuery
javascript实现移动端上传图片功能
Aug 18 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中用foreach来操作数组的代码
2011/07/17 PHP
PHP中4个加速、缓存扩展的区别和选用建议
2014/03/12 PHP
Thinkphp 框架扩展之数据库驱动常用方法小结
2020/04/23 PHP
javascript两段代码,两个小技巧
2010/02/04 Javascript
实现变速回到顶部的JavaScript代码
2011/05/09 Javascript
AngularJS的内置过滤器详解
2015/05/14 Javascript
JavaScript中的this到底是什么(一)
2015/12/09 Javascript
bootstrap多种样式进度条展示
2016/12/20 Javascript
bootstrap响应式导航条模板使用详解(含下拉菜单,弹出框)
2017/11/17 Javascript
深入理解requireJS-实现一个简单的模块加载器
2018/01/15 Javascript
vue-router重定向不刷新问题的解决
2018/06/25 Javascript
react配置antd按需加载的使用
2019/02/11 Javascript
为nuxt项目写一个面包屑cli工具实现自动生成页面与面包屑配置
2019/09/29 Javascript
js实现图片无缝循环轮播
2019/10/28 Javascript
使用vue引入maptalks地图及聚合效果的实现
2020/08/10 Javascript
js轮播图之旋转木马效果
2020/10/13 Javascript
js实现简单图片拖拽效果
2021/02/22 Javascript
Python标准库内置函数complex介绍
2014/11/25 Python
Python素数检测的方法
2015/05/11 Python
解析Python中的二进制位运算符
2015/05/13 Python
Win10下python3.5和python2.7环境变量配置教程
2018/09/18 Python
opencv-python 读取图像并转换颜色空间实例
2019/12/09 Python
Python面向对象之多态原理与用法案例分析
2019/12/30 Python
Pandas时间序列:时期(period)及其算术运算详解
2020/02/25 Python
Python Json数据文件操作原理解析
2020/05/09 Python
基于python检查矩阵计算结果
2020/05/21 Python
python和php哪个更适合写爬虫
2020/06/22 Python
CSS3实现渐变背景兼容问题
2020/05/06 HTML / CSS
canvas小画板之平滑曲线的实现
2020/08/12 HTML / CSS
Saks Fifth Avenue澳洲/亚太地区:萨克斯第五大道精品百货店
2019/06/09 全球购物
const和static readonly区别
2013/05/20 面试题
名人演讲稿范文
2013/12/28 职场文书
年会主持词结束语
2014/03/27 职场文书
《长城和运河》教学反思
2014/04/14 职场文书
2014年移动公司工作总结
2014/12/08 职场文书
毕业生就业推荐表自我鉴定
2019/06/20 职场文书