Table tr 的隔行变色

<style type="text/css">
    table{border-collapse:collapse;border:1px solid #999;}
 td{border:1px solid #999;}


 #table tr.color1{
    background-color:#fafafa;
}
    #table tr.color2{
    background-color:#f7fbfe;
}
 </style>

 

<script type="text/javascript">

   var tableid='table';      
  var overcolor='#EEEEEE';   
  var color1='#FFFFFF';       
  var color2='#F8F8F8';       
  
  var tablename=document.getElementByIdx_x_x(tableid)
  
  var tr=tablename.getElementsByTagName_r("tr")
 
     for(var i=1;i<tr.length;i++){
       tr[i].onmouseover=function(){
       this.style.background=overcolor;
     }
     tr[i].onmouseout=function(){
       if(this.rowIndex%2==0){ //获取当前行的索引
 this.style.background=color1;

 }else{
      this.style.background=color2;
    }
     }
     if(i%2==0){
        tr[i].className='color1';
     }else{
         tr[i].className='color2';
     }
    
  }
  }
  window.onload=showtable;
</script>

 

首先是: i/2==0判断是否是偶数

==================================================

jquery 判断

<script type="text/javascript">
$(document).ready(function(){
       $(".table tr:even").addClass("alt");
  $(".table tr").mouseover(function(){ 
             
        $(this).addClass("over");}).mouseout(function(){
                                //给这行添加class值为over,并且当鼠标一出该行时执行函数
        $(this).removeClass("over");}).click(function(){ //移除该行的class
  
 $(this).toggleClass("click").removeClass("alt")})
});
</script>

 

执行点击时:切换颜色.并且移除原有的背景色。

 

 

=======================方法1==============

//test
 $(".test tr:even").addClass('odd');
     $(".test tr").hover(function(){$(this).addClass('highlight')},function(){$(this).removeClass('highlight')});
  //click
  $(".test tr").click(function(){
    $(this).toggleClass('selected');
  })

 

==============方法2(推荐)===============

 $(".test tr:even").addClass('odd');
     $(".test tr").hover(function(){$(this).addClass('highlight')},function(){$(this).removeClass('highlight')});
  //默认选中添加样式
  $(this).find("input[type=checkbox]:checked").parents('tr').addClass('selected');
  //click
 
  $(".test tr").click(function(){

    if($(this).hasClass('selected')){
 
   $(this).removeClass('selected');
 
   $(this).find("input[type=checkbox]").removeAttr('checked');
  
 }else{
   $(this).addClass('selected');
    $(this).find("input[type=checkbox]").attr("checked",true); 
 }
  })

参考:http://www.codefans.net/jscss/code/2542.shtml

posted @ 2017-01-18 16:35  damon2016  阅读(1046)  评论(0编辑  收藏  举报