这是excel的界面,选中一个单元格后,该单元格,以及同行、同列的第一个单元格都呈现出特殊样式,很好地提示了用户。接下来用javascript和css实现类似效果。
关键的css如下:
css代码
td {
border-top:3px solid #FFFFFF;
border-bottom:2px solid #B3DE94;
padding:9px;
}
td.hover {/*选中的单元格*/
background-color:#595;
}
td.hover2 {/*同行同列的第一个单元格*/
background-color:#FFCC99;
}
border-top:3px solid #FFFFFF;
border-bottom:2px solid #B3DE94;
padding:9px;
}
td.hover {/*选中的单元格*/
background-color:#595;
}
td.hover2 {/*同行同列的第一个单元格*/
background-color:#FFCC99;
}
主要是背景颜色的不同。
然后用javascript循环遍历每一个单元格(不包括第一行和第一列的单元格),给它们添加鼠标经过和移出事件(当然和可以添加点击事件),然后给相关的单元格对象设定class值,鼠标移出时class设为“”就行了
javascript 写道
<script type="text/javascript">
var cells, len, tdRow, tdCol;
//保存单元格、单元格数组长度、同行,同列第一个单元格
window.onload = function() {
cells = document.getElementsByTagName("td");
len = cells.length;
for (var i = 6; i<len; i++) {
if (i%5 != 0) {
cells[i].onmouseover = function() {
this.className = "hover";
for (var j = 6; j<len; j++) {
if (cells[j] == this) {
(tdRow=cells[j%5]).className = "hover2";
(tdCol=cells[j-j%5]).className = "hover2";
document.getElementById("position").innerHTML = "x:"+(j%5)+" y:"+Math.floor(j/5);
//Firefox浏览器貌似只支持innerHTML
break;
}
}
};
cells[i].onmouseout = function() {
this.className = "";
tdRow.className = tdCol.className="";
document.getElementById("position").innerHTML = "";
//tdRow tdCol的存在就为了避免又一次的循环遍历
/*for(var j=0;j<len;j++){
if(cells[j]==this){
cells[j%5].className="";
cells[j-j%5].className="";
break;
}
}*/
};
}
}
};
//保存单元格、单元格数组长度、同行,同列第一个单元格
window.onload = function() {
cells = document.getElementsByTagName("td");
len = cells.length;
for (var i = 6; i<len; i++) {
if (i%5 != 0) {
cells[i].onmouseover = function() {
this.className = "hover";
for (var j = 6; j<len; j++) {
if (cells[j] == this) {
(tdRow=cells[j%5]).className = "hover2";
(tdCol=cells[j-j%5]).className = "hover2";
document.getElementById("position").innerHTML = "x:"+(j%5)+" y:"+Math.floor(j/5);
//Firefox浏览器貌似只支持innerHTML
break;
}
}
};
cells[i].onmouseout = function() {
this.className = "";
tdRow.className = tdCol.className="";
document.getElementById("position").innerHTML = "";
//tdRow tdCol的存在就为了避免又一次的循环遍历
/*for(var j=0;j<len;j++){
if(cells[j]==this){
cells[j%5].className="";
cells[j-j%5].className="";
break;
}
}*/
};
}
}
};
</script>
使用getElementsByTagName或getElementById取得属性,注意两个方法名称的区别:Elements的“s”
使用className属性动态设置元素的class
最后的效果如下:
经过测试Firefox和搜狗浏览器(IE)都拥有同样的效果