之前做项目的时候,也遇到过需要按照设计稿把<input type="checkbox">
和<input type="radio">
的默认样式进行修改,但发现,并没有可以重置效果的方法,之前用过-webkit-appearance的方法,但是这个只在webkit内核的浏览器里面生效,火狐不生效。
所以自己写了个js,用li来模拟复选框和单选框的效果,很简单,7行就行。
效果图:
涉及到的知识点:自定义属性来存储点击状态和原来的class名
html内容:
<div id="box"> <p>你最喜欢的运动</p> <ul> <li>爬山</li> <li>骑车</li> <li>游泳</li> <li class='hong'>篮球</li> <li class='hong'>足球</li> <li>羽毛球</li> <li>跳绳</li> <li>跑步</li> </ul> </div>
js内容:
注释比较多,是为了说明清楚,可能有点乱,能看懂的可以把注释删掉
var aLi = document.querySelectorAll('#box ul li'); /*获取所有的li,如果要用class获取,可写成document.querySelectorAll('.class')*/ for (var i=0;i<aLi.length;i++ ) { aLi[i].ifCheck = false; /*自定义属性用来表示有没有被选中,初始化设置成false,未选中*/ aLi[i].nowClass = aLi[i].className; /*自定义属性用来存储最初的className,例如html内容里的class名,hong,这样在后面添加on的class名之后,不会导致原来的class名直接被覆盖*/ aLi[i].onclick = function(){ if(this.ifCheck){ /*当点击当前li时,如果ifCheck是已经被选中状态*/ this.className = this.nowClass /*则让当前点击的li的class名等于最初的名字,也就是说把选中的on的class名去掉*/ }else{ this.className += ' on' /*如果是未选中状态,则加上on,表示被选中*/ } /*可写成三目样式 this.className = this.ifCheck?this.nowClass:this.className+' on';*/ this.ifCheck = !this.ifCheck; /*一开始未选中,点击之后变成选中,不然相反,所以要给ifCheck的属性取反*/ }; };
css样式:
#box{ width:600px; margin:50px auto; } #box p{ font-size:14px; font-weight:bold; border-bottom:1px dashed #000; line-height:30px; } #box ul{ margin-top:10px; overflow:hidden; } #box ul li{ width:67px; height:20px; float:left; background-image:url(images/ck.png); /*未选中时候的背景图*/ background-repeat:no-repeat; font-size:12px; line-height:20px; text-indent:30px; margin-right:8px; cursor:pointer; } #box ul li.on{ background-image:url(images/cked.jpg); /*选中时候的背景图*/ } #box ul li.hong{ color:red; }