본문 바로가기

삽질하기/Javascript & XML

자바스크립트 예제 - Mouse Rollover

반응형



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> Mouse Rollover </title>
<style>
   table {
      width : 300px;
      height : 150px;
      text-align : center;
      font-size : 9pt;
      font-family : gulim;
      border : 1px solid #ccc;
   }
   .mouseover {
      background-color : #EEE;
   }
   .mouseout {
     background-color : ;
   }
   .mouseclick {
      color : #FFF;
      background-color : #6482B9;
   }
</style>
<script>
   window.onload = function() {
       tdList = document.getElementsByTagName("td");
       trList = document.getElementsByTagName("tr");
       getEvent(trList, "mouseover", changeColorOver);
       getEvent(trList, "mouseout", changeColorOut);
       getEvent(tdList, "click", changeColorClick);
   }
   function getEvent(nodeList, event, observer) {
      for(var i=0; i<nodeList.length; i++) {
         if(nodeList.item(i).addEventListener) {//firefox
            e = bindAsListener(observer, nodeList.item(i));
            nodeList.item(i).addEventListener(event, e, false);
         } else {//ie
            e = bindAsListener(observer, nodeList.item(i));
            nodeList.item(i).attachEvent("on"+event, e);
         }
      }
   }
   function bindAsListener(func, obj) {
      return function() {
         return func.apply(obj, arguments);
      }
   }
   function changeColorOver() {
      if(this.className != 'mouseclick') {
         this.className = 'mouseover'
      }
   }
   function changeColorOut() {
      if(this.className != 'mouseclick') {
         this.className = 'mouseout'
      }
   }
   function changeColorClick() {
      if(this.className == 'mouseclick') {
         this.className = 'mouseout';
      } else {
         this.className = 'mouseclick';
      }
   }
</script>
</head>
<body>
<table>
<tr>
   <td>가</td>
   <td>나</td>
   <td>다</td>
</tr>
<tr>
   <td>라</td>
   <td>마</td>
   <td>바</td>
</tr>
<tr>
   <td>사</td>
   <td>아</td>
   <td>자</td>
</tr>
</table>
</body>
</html>


테이블에 롤오버하면 해당 열의 색상이 바뀌고 클릭하면 선택한 셀의 색상이 바뀌는 간단한? 예제이다.
일반적으로 HTML의 W3C표준은 구조와 표현의 분리를 지향하는데, 자바스크립트 또한 데이터와 프로그래밍을 분리하여 코딩하는 것이 효율적이다.
여기에 표현은 CSS로 처리함으로써 객체 지향의 MVC적인 페이지가 될 것이다.