您的位置:首页 > Web前端 > JQuery

模拟Jquery addClass() removeClass() 并应用于隔行变色 高亮当前行

2012-10-24 17:16 309 查看
function addClass(obj,className){
if(obj.getAttribute('class')){
obj.setAttribute('class',obj.getAttribute('class')+' '+className);
}else{
obj.setAttribute('class',className);
}
}
function removeClass(obj,className){
if(!obj.getAttribute('class')) return false;
var oldClass=obj.getAttribute('class');
obj.setAttribute('class',oldClass.replace(className,''));
}
function changeTableColor(oddColor,evenColor){
var tables=document.getElementsByTagName('table');
for(var i=0;i<tables.length;i++){
var table=tables[i];
var childs=table.childNodes;
for(var j=0;j<childs.length;j++){
var child=childs[j];
if(child.nodeName=='TBODY'){
var trs=child.childNodes;
for(var x=0;x<trs.length;x++){
if(trs[x].nodeName=='TR'){
var tr=trs[x];
if(x%4==0 ){
//trs[x].style.backgroundColor=oddColor;
addClass(trs[x],'oddColor');
}
if(x%4==2){
addClass(trs[x],'evenColor');
//trs[x].style.backgroundColor=evenColor;
}
}
}
}
}
}
}
function highlighttr(color){
var trs=document.getElementsByTagName('tr');
for(var x=0;x<trs.length;x++){
var tr=trs[x];
var oldColor=tr.style.backgroundColor;

tr.onmouseover=function(){
//this.style.backgroundColor=color;
addClass(this,'highlight');
}
tr.onmouseout=function(){
removeClass(this,'highlight');
//this.style.backgroundColor=oldColor;
}
}
}
window.onload=function(){
changeTableColor('#ddd','#eee');
highlighttr('#9cf');
}
<!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>
<title></title>
<style>
*{margin:0;padding:0;position:relative;}
select,button{line-height:30px;padding:5px;}
table{margin:auto;border:1px solid #333;}
caption{margin:auto;padding:0.2em;font-size:1.2em;font-weight:bold;}
th{
font-weight:normal;font-style:italic;text-align:left;border:1px dotted #699;
background-color:#9cc;color:#000;
}
th,td{width:10em;padding:.5em;}
body{font-family:'Helvetica','Arial',sans-serif;color:#000;}
.oddColor{background-Color:#ddd;}
.evenColor{background-Color:#eee;}
.highlight{background-Color:#9cf;}
</style>
<script type="text/javascript" src="myjquery.js"></script>
</head>
<body>
<table>
<caption>Itinerary</caption>
<thead>
<tr>
<th>When</th>
<th>Where</th>
</tr>
</thead>
<tr>
<td>July 9th</td>
<td>Portland,<abbr title='Oregon'>OR</abbr></td>
</tr>
<tr>
<td>June 10th</td>
<td>Seattle,<abbr title='Washington'>WA</abbr></td>
</tr>
<tr>
<td>December 12th</td>
<td>Sacramento,<abbr title='California'>CA</abbr></td>
</tr>
<tr>
<td>Octoboer 13th</td>
<td>New York,<abbr title='Oregon'>NY</abbr></td>
</tr>
<tr>
<td>May 14th</td>
<td>DownCity,<abbr title='Washington'>DC</abbr></td>
</tr>
<tr>
<td>June 15th</td>
<td>Washinton,<abbr title='California'>WT</abbr></td>
</tr>
</table>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: