JavaScript 双击选中表格单元格,类似Windows系统一样的效果,使用JS获取表格的“TD”标签,加入JavaScript动作,因此这里的“TD”你完全可以换成“DD”,也就是把Table换成Div结构同样生效,不过你要对相应的CSS代码做些修改:
<html>
<head>
<title>双击选中单元格-www.codefans.net</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<style type="text/css">
.STYLE3 {font-size: 13px; color: #FF0000; }
.STYLE4 {font-size: 12px}
</style>
<body>
<table id="table1" width="500" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#CCCCCC">
<tr>
<td width="113" height="24" align="center" bgcolor="#FFFFFF"><span class="STYLE3">商品名称</span></td>
<td width="83" align="center" bgcolor="#FFFFFF"><span class="STYLE3">数量</span></td>
<td width="139" align="center" bgcolor="#FFFFFF"><span class="STYLE3">价格</span></td>
<td width="142" align="center" bgcolor="#FFFFFF"><span class="STYLE3">合计</span></td>
</tr>
<tr>
<td height="20" align="center" bgcolor="#FFFFFF" class="STYLE4">源码爱好者</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">1</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">888</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">888</td>
</tr>
<tr>
<td height="20" align="center" bgcolor="#FFFFFF" class="STYLE4">数码相机</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">2</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">2400</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">4800</td>
</tr>
<tr>
<td height="20" align="center" bgcolor="#FFFFFF" class="STYLE4">手机</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">4</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">2400</td>
<td align="center" bgcolor="#FFFFFF" class="STYLE4">9600</td>
</tr>
</table>
<script language="javascript">
var lastSelection = null;
function select(element){
var e, r, c;
if(element == null){
e = event.srcElement;//获取body元素的原始记录
}else{
e = element;
}
if(e.tagName == "TD"){
c = findcell(e);
if(c != null){
if(lastSelection != null){
deselectroworcell(window.lastSelection);
}
selectroworcell(c);
lastSelection = c;
}
}
window.event.cancelBubble = true;//取消冒泡语句,用于防止向下一个外层对象冒泡
}
table1.onclick=select;
function findcell(e){
if(e.tagName == "TD"){
return e;
}else if(e.tagName == "BODY"){
return null;
}else{
return findcell(e.parentElement);
}
}
function selectroworcell(r){
r.runtimeStyle.backgroundColor="darkblue";
r.runtimeStyle.color="white";
}
function deselectroworcell(r){
r.runtimeStyle.backgroundColor = "";
r.runtimeStyle.color = "";
}
</script>
</body>
</html>