行爲 樣式 結構相分離的頁面html
JS CSS HTMLide
DOM 0寫法函數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1" width="300px"> <tr onmousemove="t1(0);" onmouseout="t2(0)"><td>1</td><td>2</td><td>3</td></tr> <tr onmousemove="t1(1);" onmouseout="t2(1)"><td>1</td><td>2</td><td>3</td></tr> <tr onmousemove="t1(2);" onmouseout="t2(2)"><td>1</td><td>2</td><td>3</td></tr> </table> <script> //DOM 0實現的效果 function t1(n){ var mytrs = document.getElementsByTagName('tr')[n]; console.log(mytrs); mytrs.style.backgroundColor = "red"; } function t2(n){ var mytrs = document.getElementsByTagName('tr')[n]; console.log(mytrs); mytrs.style.backgroundColor = ""; } </script> </body> </html> Demo
DOM 1寫法this
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> .c1{ background-color: cadetblue; width: 300px; } </style> <body> <div class="c1"> <table border="1" width="300px"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> </div> <script> //DOM 1實現的效果 var myTrs = document.getElementsByTagName("tr"); var len = myTrs.length; for(var i=0;i<len;i++){ myTrs[i].onmouseover = function(){ //綁定事件 this.style.backgroundColor = "red"; //誰調用這個函數,這個this就指向誰 } myTrs[i].onmouseout = function(){ this.style.backgroundColor = ""; } } </script> </body> </html>
第一種很是低效,每次都要在標籤上綁定。spa
第二種相對高效一點,首先獲取DOM對象,而後一次綁定。code