(一) 用图片模拟 用到的三个图片如下: 0.gif: 1.gif: 2.gif: 代码如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>三态的checkbox</title> <script language="javascript"> //预载图片 var notChkImg = new Image(); //没有选中 notChkImg.src = "images/0.gif" var halfChkImg = new Image();//半选中 halfChkImg.src = "images/1.gif" var chkImg = new Image(); //选中 chkImg.src = "images/2.gif"
function myHalfCheckBox(img,obj)
/* 参数说明 img 模拟的图片 obj 可以提交的那个checkbox img.checkedState 表示选中的状态,0,1,2分别表示没有选中,半选中,全选中 在半选中的状态obj的值是以halfChecked__开头的,需要截去前面的"halfChecked__"才是真正的值 */ { if(img.src.indexOf("0.gif")>0) //没有选中的状态 { img.src = halfChkImg.src; obj.checked = true; obj.value = "halfChecked__" + img.value img.checkedState = 1;
}else if(img.src.indexOf("1.gif")>0) //半选中的状态 { img.src = chkImg.src; obj.disabled = false; obj.checked = true; obj.value = img.value img.checkedState = 2;
}else //选中的状态 { img.src = notChkImg.src; obj.disabled = false; obj.checked = false; obj.value = img.value img.checkedState = 0; }
} </script> </head>
<body> <img id=img1 src="images/0.gif" width="16" height="16" onClick="myHalfCheckBox(this,submitChkbox)" checkedState="0" value="test"> <input style="display:none" type="checkbox" name="submitChkbox" value="test"> <input type="button" value="得到选中的状态" onclick="alert(img1.checkedState)"> <input type="button" value="得到选中的值" onclick="alert(img1.value)"> <input type="button" value="得到隐藏的checkbox的值" onclick="alert(submitChkbox.value)">
</body> </html>
(二)用checkbox上覆盖一个透明的层来实现 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title></title> <script language="JavaScript" type="text/JavaScript"> <!-- function myHalfCheckBox(obj) { if(obj.disabled) //半选中状态 { obj.disabled = false; //设置为选中的状态 }else if(obj.checked)//选中状态 { obj.checked = false; //设置为没有选中的状态 }else //没有选中的状态 { obj.disabled = true; //设置为半选中状态 obj.checked = true; } } //--> </script> </head>
<body> <div id="idDiv" onClick="myHalfCheckBox(halfChkBoxTest)" onselectstart='return false;' style="position:absolute; cursor:default;left:12px; top:11px; width:16px; height:19px; z-index:1;filter : progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=0,finishOpacity=100);"> <table width="100%" height="100%" border="0"> <tr> <td> </td> </tr> </table> </div> <input name="halfChkBoxTest" type="checkbox" value="1"> </body> </html>
(三)其他的一些思路,代码没有写 1)用input type="image"来模拟,和用图片差不多。
2)用用text来模拟。主要思路是在选中状态设置text的value为“∨”,在半选中状态通过修改text的字体的样式来表示,没有选中状态设置text为空,我在CSDN上有个帖子中有个用用text模拟的 checkbox的例子。
3)如果你不闲麻烦的话在IE5+中通过VML自己来画,呵呵,有点夸张。 
|