DIV CSS 佈局教程網

用 JS 做出滑鼠移過時整列變色的表格
編輯:JavaScript綜合知識     

讓表格在滑鼠移入某一列時整列高亮,是提升可讀性的常見做法。以下透過 onmouseover 與 onmouseout,在移入時記下原本的底色再換成高亮色,移出時還原。

<script>
function overIt(){
  var the_obj = event.srcElement;
  if(the_obj.tagName.toLowerCase() == "td"){
    the_obj = the_obj.parentElement;
    the_obj.oBgc = the_obj.currentStyle.backgroundColor; // 記下原底色
    the_obj.oFc  = the_obj.currentStyle.color;
    the_obj.style.backgroundColor = '#71BAF0';
    the_obj.style.color = '';
  }
}
function outIt(){
  var the_obj = event.srcElement;
  if(the_obj.tagName.toLowerCase() == "td"){
    the_obj = the_obj.parentElement;
    the_obj.style.backgroundColor = the_obj.oBgc; // 還原
    the_obj.style.color = the_obj.oFc;
  }
}
</script>

<table border="1" width="400" onmouseover="overIt()" onmouseout="outIt()">
  <tr bgColor="#111111"><td>aaa</td><td>aaa</td><td>aaa</td><td>aaa</td></tr>
  <tr bgColor="#222222"><td>aaa</td><td>aaa</td><td>aaa</td><td>aaa</td></tr>
</table>

要點在於:事件來源 event.srcElement 往往是最內層的 td,因此先判斷標籤是否為 td,再取其父節點 parentElement(也就是 tr)來改底色,這樣整列才會一起變色。移入前先把原本的 bgColor 存起來,移出時再寫回,就能正確還原到每列各自的底色。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved