隔行换色table以及鼠标滑过换色
以前对编写javascript的东西一直比较抗拒,觉得这东西比较扯,最近自己学了学javascript以及css,觉得其实也挺简单的,而且越来越感觉javascript是个很好的东西。
以前觉得网页上有的表格特效很好看,自己现在也写了一个,首先是要隔行换色,然后就是当鼠标滑过的时候有变色的效果,其实挺简单的,javascript+css很容易就可以搞定的。。。。。
| name | time | home |
|---|---|---|
| fjs1 | 1992-03-28 | 杭州 |
| fjs2 | 1992-03-28 | 杭州 |
| fjs3 | 1992-03-28 | 杭州 |
首先是定义了两种tr的样式,这样来实现表格的隔行换色:
tr.one{
background-color:#66FFFF;
}
tr.two{
background-color:#F8F8F8;
}
其次就是在页面载入的时候通过javascript来设置每一行的css:
<script type="text/javascript">
function showTable(){
var table=document.getElementById("table");
var trs=table.getElementsByTagName("tr");
var i;
var color1='#FFFFFF';
var color2='#F8F8F8';
for(i=1;i<trs.length;i++){
if(i%2==0){
trs[i].className='two';
}else{
trs[i].className='one';
}
trs[i].onmousemove=function(){
this.className='over';
}
trs[i].onmouseout=function(){
if(this.rowIndex%2==0){
this.className='two';
}else{
this.className='one';
}
}
}
}
window.onload=showTable;
</script>
前段代码还包括了为每一个tr添加事件,当鼠标的滑过的时候要更改行的样式,当然也还有恢复的函数,其实要实现滑过变色通过css里面定 义:hover就能够很容易的实现,但是这样浏览器的支持确不是很好,例如IE就不支持,所以就通过这个稍微显得比较麻烦的方法来实现了。。。
页面源码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style type="text/css">
#table{
font-size:18px;
font-weight:bold;
border:1px dashed #000000;
width:100%;
}
tr.one{
background-color:#66FFFF;
}
tr.two{
background-color:#F8F8F8;
}
tr.over{
background-color:#0066FF;
}
</style>
<script type="text/javascript">
function showTable(){
var table=document.getElementById("table");
var trs=table.getElementsByTagName("tr");
var i;
var color1='#FFFFFF';
var color2='#F8F8F8';
for(i=1;i<trs.length;i++){
if(i%2==0){
trs[i].className='two';
}else{
trs[i].className='one';
}
trs[i].onmousemove=function(){
this.className='over';
}
trs[i].onmouseout=function(){
if(this.rowIndex%2==0){
this.className='two';
}else{
this.className='one';
}
}
}
}
window.onload=showTable;
</script>
</head>
<body>
<table id="table" align="center">
<tr>
<th>name</th>
<th>time</th>
<th>home</th>
</tr>
<tr>
<td>fjs1</td>
<td>1992-03-28</td>
<td>杭州</td>
</tr>
<tr>
<td>fjs2</td>
<td>1992-03-28</td>
<td>杭州</td>
</tr>
<tr>
<td>fjs3</td>
<td>1992-03-28</td>
<td>杭州</td>
</tr>
</table>
</body>
浙公网安备 33010602011771号