본문 바로가기

Dev. Language/Javascript

이벤트, 이벤트 핸들러 실습

1. cross-browsing (파폭, IE 연동하기 위한 처리)
- mouseEvent 예제

<?xml version="1.0" encoding="EUC-KR" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript" language="javascript">
//<![CDATA[
       
// Cross-Browsing
function mouseDown(nsEvent){   
    var theEvent = nsEvent ? nsEvent : window.event; // nsEvent : Firefox ver. / window.event : IE ver.
    var locString="X = "+theEvent.screenX + " Y = "+theEvent.screenY;
   
    alert(locString); 
}

document.onmousedown=mouseDown;
//]]>
</script>
</body>
</html>

2. 이벤트 핸들러 사용 예제
<?xml version="1.0" encoding="EUC-KR" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
//<![CDATA[
    function show(evnt){
        // 객체 탐지
        var btn1 = document.getElementById("btn1"); // btn1 ID를 가진 element(객체)를 가진 btn1 객체
        alert(btn1.type);

        // 이벤트 객체 획득(cross-browsing)
        var theEvent = evnt ? evnt : window.event; // cross - browsing
        alert(theEvent);

        // 이벤트 대상객체 획득(cross-browsing)
        var theEventTarget = theEvent.target ? theEvent.target : theEvent.srcElement;
        alert(theEventTarget);
    }

       function getText(evnt) {
           var theEvent = evnt ? evnt : window.event; // cross - browsing
          alert(String.fromCharCode(theEvent.keyCode)); // 아스키코드 출력
    }

    function addHandler() {
        var txt1 = document.getElementById("text1");
        txt1.onkeydown = getText;
    }
    window.onload = addHandler;
//]]>
</script>
</head>
<body>
<input type = "button" id = "btn1" value="버튼" onclick="show(event);"/>
<input type = "text" id = "text1" size="10" />

</body>
</html>