웹페이지

JAVASCRIPT SETP 11 - MouseEvent

IT의 큰손 2023. 4. 21. 12:48
728x90

★ 마우스 관련 이벤트, MouseEvent

  • onmouseXXX
  • 1. onmouseover(= onmouseenter)
    • 해당 객체의 영역에 마우스(커서)가 진입하는 순간 발생
function message(txt) {
    var now = new Date();
    txt1.value = txt + '-' + now.toLocaleDateString() + '\r\n' + txt1.value;
}

txt1.onmouseover = m1;
function m1() {
    message('mouseover');
    //window.document.body.bgColor = 'gold'; //배경 색 변경
}
  • 2. onmouseout(= onmouseleave)
    • 해당 객체의 영역에 마우스(커서)가 빠져나가는 순간 발생
function message(txt) {
    var now = new Date();
    txt1.value = txt + '-' + now.toLocaleDateString() + '\r\n' + txt1.value;
}

txt1.onmouseout = m2;
function m2() {
    message('mouseout');
    //window.document.body.bgColor = 'white'; //배경색 원상복귀
}
  • 3. onmousedown
    • 해당 객체의 영역에서 마우스 버튼을 누르는 순간 발생
function message(txt) {
    var now = new Date();
    txt1.value = txt + '-' + now.toLocaleDateString() + '\r\n' + txt1.value;
}

txt1.onmousedown = m3;
function m3() {
    message('mousedown');
}
  • 4. onmouseup
    • 해당 객체의 영역에서 마우스 버튼은 때는 순간 발생
function message(txt) {
    var now = new Date();
    txt1.value = txt + '-' + now.toLocaleDateString() + '\r\n' + txt1.value;
}

txt1.onmouseup = m4;
function m4() {
    message('mouseup');
}
  • 5. onmousemove
    • 해당 객체의 영역에서 마우스가 움직일때마다 발생
function message(txt) {
    var now = new Date();
    txt1.value = txt + '-' + now.toLocaleDateString() + '\r\n' + txt1.value;
}
        
txt1.onmousemove = m5;
function m5() {
    message('mousemove');
    // window.document.body.bgColor = 'white';
}
  • 6. event.buttons
    • 마우스 어떤 버튼이 눌렸는지? 왼쪽(1), 오른쪽(2), 왼쪽+오른쪽(3), 휠버튼(4)
function m3() {

    //마우스 버튼
    //event.buttons

    message(event.buttons);
}
//오른쪽 마우스 버튼 클릭 금지!
if (event.buttons == 2){
    alert('오른쪽 마우스 버튼 클릭 금지!!');
}
  • 마우스 커서 좌표 
  • 1. x, y
    • 문서 좌측 상단을 기준
    • 비표준(MS-IE) > 비권장
message(event.x + ',' + event.y);
  • 2. clientX, clientY(주로 사용)
    • 문서 좌측 상단을 기준
    • 표준 > 권장
    • CSS > position : absolute;
message(event.clientX + ',' + event.clientY);
  • 3. screenX, screenY
    • 모니터 좌측 상단을 기준
message(event.screenX + ',' + event.screenY);
  • 4. offsetX, offsetY(주로 사용)
    • 이벤트 객체의 좌측 상단을 기준
    • 나 자신이 기준
    • CSS > position : relative; 와 비슷함
message(event.offsetX + ',' + event.offsetY);

 

 

 

■ 기본코드

<style>
    textarea, input {
        display: block;
        margin-bottom: 10px;
    }

    textarea {
        width : 500px;
        height: 300px;
        outline : none;
        resize : none;
    }
</style>

<body>
    <h1>마우스 관련 이벤트</h1>

    <form name="form1">
        <textarea name="txt1"></textarea>
        <input type="button" value="확인" name="btn1">
    </form>
</body>

 

 

728x90