纯js模拟 radio和checkbox控件
2020-12-13 04:41
标签:des style blog class code c 代码待优化,功能实现了,不兼容ie8以上, 相同name的radio可以实现切换的操作, 分享代码,共同学习进步 纯js模拟 radio和checkbox控件,搜素材,soscw.com 纯js模拟 radio和checkbox控件 标签:des style blog class code c 原文地址:http://www.cnblogs.com/z-Relix/p/3732612.htmldoctype html>
html>
head>
meta charset="utf-8">
title>title>
style>
.radiobox,
.checkbox {
width: 10px;
height: 10px;
padding: 2px;
border: solid #ccc 1px;
}
.radiobox .rb_action,
.checkbox .cb_action {
width: 8px;
height: 8px;
border: solid #ccc 1px;
}
.radiobox .rb_action:hover,
.checkbox .cb_action:hover {
background: #95d692;
}
.radiobox {
border-radius: 10px;
}
.radiobox .rb_action {
border-radius: 8px;
}
style>
head>
body>
input type="checkbox"/>
input type="checkbox"/>
input type="radio" name=‘demo‘/>
input type="radio" name=‘demo‘/>
input type="radio" />
script src="script/jquery.min.js">script>
script>
var target = document.getElementsByTagName(‘input‘);
len = target.length, i = 0, id = 0;
for( ; i len; i++) {
var elem = target[i],
type = elem.getAttribute(‘type‘);
switch(type) {
case ‘checkbox‘: checkRadioBoxFunc.call(elem); break;
case ‘radio‘ : checkRadioBoxFunc.call(elem, ‘radio‘); break;
}
}
function checkRadioBoxFunc(radio) {
// 绑定id
this.setAttribute(‘id‘, id);
// 建立原始控件信息库
var CheckRadioBoxInfo = {
//原始控件四边缘坐标
//‘coord4side‘: {‘top‘: ‘‘, ‘right‘: ‘‘, ‘bottom‘: ‘‘, ‘left‘: ‘‘}
// 原始控件偏移坐标
‘offset‘: {
‘top‘: this.offsetTop + ‘px‘,
‘left‘: this.offsetLeft + ‘px‘
}
};
// 隐藏原始控件
this.style.visibility = ‘hidden‘;
// 创建新控件结构
var newNode = document.createElement(‘div‘),
pClassName = !radio ? ‘checkbox‘ : ‘radiobox‘,
tClassName = !radio ? ‘cb_action‘ : ‘rb_action‘,
radionName = !radio ? ‘‘ : this.getAttribute(‘name‘);
newNode.style.cssText = ‘position:absolute;top:‘ + CheckRadioBoxInfo.offset.top + ‘;left:‘ + CheckRadioBoxInfo.offset.left + ‘;‘;
newNode.innerHTML = ‘