首页 > 其他 > 详细

我封装的第一个组件,单选按钮

时间:2014-11-25 09:08:53      阅读:355      评论:0      收藏:0      [点我收藏+]

在用别人的组件的时候,总是感觉东西太大,用起来还得查看,别人是怎么写的,如何用,所以自己也开始学习一下封装一个组件:在这里封装了一个自定义的单选框:
html代码 :

 

<form id="form1" action="http://www.zhinengshe.com/" method="get">
	性别:
	<input type="radio" name="sex" value="男" />男
	<input type="radio" name="sex" value="女" />女
	<br />
	<input type="submit" />
</form>

 css 部分:

.my_radio_off{width:18px; height:18px; display:inline-block; background: url(radio.gif) no-repeat 0 0;}
.my_radio_on{width:18px; height:18px; display:inline-block; background: url(radio.gif) no-repeat 0 -18px;}

 JS部分,在写之前,我先写了一个ready封装,好用ready,其实大家在做的时候,可以先把ready封好,回头直接调用,在这里把这个JS文件保存为:radio.js

 

function $(fn){
	if(document.addEventListener){
		document.addEventListener(‘DOMContentLoaded‘,fn,false);
	}else{
		document.onreadystatechange=function(){
			fn();
		}
	}
};


(function(){

	var added=false;

	window.myRadio=function (name){
		var aSe=document.getElementsByName(name);
		var aSpan=[];

		for(var i=0; i<aSe.length; i++){
			var oSpan=document.createElement(‘span‘);
			oSpan.className=‘my_radio_off‘;
			aSpan.push(oSpan);

			aSe[i].parentNode.insertBefore(oSpan,aSe[i]);
			aSe[i].style.display=‘none‘;
			(function(index){
				oSpan.onclick=function(){
					for(var i=0; i<aSpan.length; i++){
						aSpan[i].className=‘my_radio_off‘;
					}
					this.className=‘my_radio_on‘;
					aSe[index].checked=true;
				}
			})(i);
		}
	};

	if(added==true)return;
	added=true;

	var oLink=document.createElement(‘link‘);
	oLink.href=‘radio.css‘;
	oLink.rel=‘stylesheet‘;
	var oHead=document.getElementsByTagName(‘head‘)[0];
	oHead.appendChild(oLink);

})()

  调用:

<script src="radio.js"></script>
<script>
$(function(){
	myRadio(‘sex‘);
})
</script>

  

 

 

我封装的第一个组件,单选按钮

原文:http://www.cnblogs.com/wujidns/p/4120118.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!