国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jscript > 用JavaScript更改input中radio和checkbox样式

用JavaScript更改input中radio和checkbox样式

来源:程序员人生   发布时间:2014-04-07 09:34:49 阅读次数:2666次

  随着前端技术的进步和发展,传统的表单样式已经不能满足需求,由于美观上的要求,网上现在出现了很多的这种表单美化插件。上网搜了一下,还真的不少,不过都没怎么用,我不喜欢在网页的头部加载一群js,有的网页头部这样的标签排列很长,很多的js一起加载进来,之间可能会出现bug不说,就是当初更改起来也不是很方便。

  插件有插件的好处,有它的便捷性。如果为了效率,使用插件值得考虑。如果是为了研究学习,建议还是自己写比较好。下面写了一个简单的radio和checkbox的美化程序。


提示:可修改后代码再运行!

  HTML代码:

单选:
<span><input type="radio" name="sex" value="boy" checked="checked" id="sex_boy" /></span><label for="sex_boy">男</label>
<span><input type="radio" name="sex" value="girl" id="sex_girl" /></span><label for="sex_girl">女</label>

多选:
<span><input type="checkbox" name="hobby" checked="checked" id="hobby1" /></span><label for="hobby1">xhtml</label>
<span><input type="checkbox" name="hobby" id="hobby2" /></span><label for="hobby2">CSS</label>
<span><input type="checkbox" name="hobby" id="hobby3" /></span><label for="hobby3">Javascript</label>
<span><input type="checkbox" name="hobby" id="hobby4" /></span><label for="hobby4">Flash</label>
<span><input type="checkbox" name="hobby" id="hobby5" /></span><label for="hobby5">Ajax</label>
<span><input type="checkbox" name="hobby" id="hobby6" /></span><label for="hobby6">AS</label>
<span><input type="checkbox" name="hobby" id="hobby7" /></span><label for="hobby7">Flex</label>
<span><input type="checkbox" name="hobby" id="hobby8" /></span><label for="hobby8">PHP/.NET/JSP</label>

Javascript部分代码:

function radio_style(){
if(gettag("input")){
var r=gettag("input");
function select_element(obj,type){
obj.parentNode.style.background="url(input_style.gif) no-repeat -15px 0px";
if(obj.type=="checkbox"){
obj.parentNode.style.background="url(input_style.gif) no-repeat -15px -15px";
}
if(type){
obj.parentNode.style.background="url(input_style.gif) no-repeat 0px 0px";
if(obj.type=="checkbox"){obj.parentNode.style.background="url(input_style.gif) no-repeat 0px -15px";}
}
}
for(var i=0;i<r.length;i++){
if(r[i].type=="radio"||r[i].type=="checkbox"){
r[i].style.opacity=0;r[i].style.filter="alpha(opacity=0)";
r[i].onclick=function(){select_element(this);unfocus();}
if(r[i].checked==true){select_element(r[i]);}else{select_element(r[i],1);}
}
}
function unfocus(){
for(var i=0;i<r.length;i++){
if(r[i].type=="radio"||r[i].type=="checkbox"){if(r[i].checked==false){select_element(r[i],1)}}
}
}
}
}

CSS部分:

.input_style span{display:inline-block; width:15px; height:15px; text-align:left; vertical-align:middle; _overflow:hidden;}
.input_style label{ padding:0px 6px; cursor:pointer;}
.input_style input{ cursor:pointer;}

其实原理很简单,就是让input透明度变为0,然后给input添加一个背景,当鼠标选择的时候,更换其背景为选中状态即可

稍做了一下改动,可以控制样式是否加载:


提示:可修改后代码再运行!

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------

上一篇 JavaScript的FileSystemObject对象写入文本文件内容

下一篇 Oracle流程分析套件助东方海外扩大SOA效用

分享到:
------分隔线----------------------------
为码而活
积分:4237
15粉丝
7关注
栏目热点
关闭
程序员人生