隔行变色有很多种实现方法,自己也整理了一下,归纳三种,分享出来,仅供参考
1. html 如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style> 7 8 div{ 9 height:30px; 10 border:1px solid gray; 11 } 12 </style> 13 </head> 14 <body> 15 <div></div> 16 <div></div> 17 <div></div> 18 <div></div> 19 <div></div> 20 <div></div> 21 <div></div> 22 <div></div> 23 <div></div> 24 <div></div> 25 <div></div> 26 <div></div> 27 <div></div> 28 <div></div> 29 <div></div> 30 <div></div> 31 <div></div> 32 <div></div> 33 <div></div> 34 <div></div> 35 <div></div> 36 <div></div> 37 <div></div> 38 </body> 39 </html>
1.1 第一种实现方法:流程式的
1 window.onload=function(){ 2 var adiv = document.querySelectorAll('div'); 3 for(var i=0;i<adiv.length;i++){ 4 if(i%2==0){ 5 adiv[i].style.background = 'green'; 6 }else{ 7 adiv[i].style.background = 'blue'; 8 } 9 }; 10 var oldcolor = null; 11 for(var i=0;i<adiv.length;i++){ 12 adiv[i].onmouseover = function(){ 13 oldcolor = this.style.background; 14 this.style.background = 'gray'; 15 }; 16 adiv[i].onmouseout = function(){ 17 this.style.background = oldcolor; 18 }; 19 }; 20 }
1.2 第二种实现方法:面向对象式的
1 window.onload=function(){ 2 var obj = { 3 adiv :[], 4 setdiv : function(){ 5 this.adiv = document.querySelectorAll('div'); 6 }, 7 init : function(){ 8 this.setdiv(); 9 for(var i=0;i<this.adiv.length;i++){ 10 if(i%2==0){ 11 this.adiv[i].style.background = 'green'; 12 }else{ 13 this.adiv[i].style.background = 'blue'; 14 } 15 }; 16 }, 17 toogle:function(){ 18 var oldcolor = null; 19 var that = this; 20 for(var i=0;i<that.adiv.length;i++){ 21 that.adiv[i].onmouseover = function(){ 22 oldcolor = this.style.background; 23 this.style.background = 'gray'; 24 }; 25 that.adiv[i].onmouseout = function(){ 26 this.style.background = oldcolor; 27 }; 28 }; 29 } 30 }; 31 obj.init(); 32 obj.toogle(); 33 }
1.3 第三种实现方法:面向对象的原型对象式的
1 window.onload = function(){ 2 3 function OTdiv(){ 4 this.adiv = document.querySelectorAll('div'); 5 }; 6 OTdiv.prototype.init = function(){ 7 for(var i=0;i<this.adiv.length;i++){ 8 if(i%2==0){ 9 this.adiv[i].style.background = 'green'; 10 }else{ 11 this.adiv[i].style.background = 'blue'; 12 } 13 }; 14 }; 15 OTdiv.prototype.toogle = function(){ 16 var oldcolor = null; 17 var that = this; 18 for(var i=0;i<that.adiv.length;i++){ 19 that.adiv[i].onmouseover = function(){ 20 oldcolor = this.style.background; 21 this.style.background = 'gray'; 22 }; 23 that.adiv[i].onmouseout = function(){ 24 this.style.background = oldcolor; 25 }; 26 }; 27 }; 28 var odiv = new OTdiv(); 29 odiv.init(); 30 odiv.toogle(); 31 };
经过测试,三种方法都可以运行出结果:设定div 隔行颜色变换,当鼠标移入时,当前div颜色改变,鼠标移出时,当前div颜色恢复,如下:
http://www.cnblogs.com/huanying2015 博客随笔大多数文章均属原创,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利