两个可以半选的checkbox

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 awaysrain 的 blog

(一) 用图片模拟
用到的三个图片如下:
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>&nbsp;</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自己来画,呵呵,有点夸张。

本文关键:半选 三态 checkbox
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top