无论是使用哪种方式实现隔行变色的效果,它的思路都是一样的:
1.定义很多个div
2.给div 加背景
3.鼠标移动到div上时,当前div 背景变色
4.鼠标移出div时,当前div背景恢复
以上4点就是隔行变色的思路流程,任何形式的实现方式,都要依照以上的思路来,否则将不会达到效果-----这是本质。因为经常会弄反,写着写着就忘记之前要干什么事了,所以此处写出来,当做提示信息
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 <style> 9 div { 10 border: 1px solid #000; 11 margin: 10px; 12 border: 1px solid #000; 13 height: 10px; 14 padding: 10px; 15 } 16 .even-color { 17 background: #eee; 18 } 19 .odd-color { 20 background: #ccc; 21 } 22 .active { 23 background: red; 24 } 25 </style> 26 </head> 27 <body> 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 <div></div> 39 <div></div> 40 <div></div> 41 <div></div> 42 <div></div> 43 </body> 44 </html>
js 常规实现方式(es5):
1 window.onload = function() { 2 var adiv = document.querySelectorAll("div"); 3 var oldColor = ''; 4 adiv.forEach(function(ele, index) { 5 ele.className = (index % 2 == 0) ? 'even-color' : 'odd-color'; 6 }); 7 adiv.forEach(function(ele, index) { 8 ele.onmouseover = function() { 9 oldColor = this.className; 10 this.className = 'active'; 11 } 12 ele.onmouseout = function() { 13 this.className = oldColor; 14 } 15 }); 16 }
js es6实现方式:
1 window.onload = function() { 2 let adiv = document.querySelectorAll("div"); 3 let oldColor = ''; 4 adiv.forEach((ele, index) => { 5 ele.className = (index % 2 == 0) ? 'even-color' : 'odd-color'; 6 }); 7 adiv.forEach((ele, index) => { 8 ele.onmouseover = () => { 9 oldColor = ele.className; 10 ele.className = 'active'; 11 }; 12 ele.onmouseout = () => { 13 ele.className = oldColor; 14 } 15 }); 16 };
js es6 及html5 ele.classList.add() & ele.classList.remove() 方法实现:
1 window.onload = function() { 2 let adiv = document.querySelectorAll("div"); 3 let oldColor = ''; 4 adiv.forEach((ele, index) => { 5 ele.className = (index % 2 == 0) ? 'even-color' : 'odd-color'; 6 }); 7 adiv.forEach((ele, index) => { 8 ele.onmouseover = () => { 9 ele.classList.add('active'); 10 }; 11 ele.onmouseout = () => { 12 ele.classList.remove('active'); 13 } 14 }); 15 }
运行结果都是相同的: