JS基礎学習四:バインドイベント

2954 ワード

イベントの追加
IE: attachEvent
Other: addEventListener
var button = document.getElementById("buttonId");
if(button.addEventListener){
    button.addEventListener("click",eventFunction,false);
}else if(button.attachEvent){
    button.attachEvent("onclick",eventFunction);
}

イベントの削除
IE: detachEvent
Other: removeEventListener
イベントバブルメカニズム
IE:イベントが発生した場所からトリガーされ、DOM構造の上層に泡が立ちます
Other:イベントはターゲット要素に下に沈んでから上に泡が立ちます
     addEventListener( ,[true|false])
  • true:沈下時にイベントをキャプチャ
  • false:上向きに泡が立ったときのイベント
  • イベントの発泡を停止するには:
    IE: window.event.cancelBubble=false;
    Other: e.stopPropagation();
    実験の例:
    function bindEvent() {
    	var button = document.getElementById("buttonId");
    	if (button.addEventListener) {
    		alert("Other browser");
    		//button.addEventListener("click",showEvent,false);
    		//button.addEventListener("click",showEvent2,false);
    		button.addEventListener("click", showEvent, true);
    		button.addEventListener("click", showEvent2, true);
    	} else if (button.attachEvent) {
    		alert("IE browser");
    		button.attachEvent("onclick", showEvent);
    		button.attachEvent("onclick", showEvent2);
    	}
    }
    
    function removeEvent() {
    	var button = document.getElementById("buttonId");
    	if (button.removeEventListener) {
    		alert("Other browser");
    		//button.removeEventListener("click",showEvent,false);
    		button.removeEventListener("click", showEvent, true);
    	} else if (button.detachEvent) {
    		alert("IE browser");
    		button.detachEvent("onclick", showEvent);
    	}
    }
    
    function showEvent(e) {
    	if (window.event != undefined) {
    		window.event.cancelBubble = true;
    	} else if (e.stopPropagation) {
    		e.stopPropagation();
    	}
    	alert("Event here!");
    }
    
    function showEvent2() {
    	alert("Other event here!");
    }
    
    function divEvent() {
    	alert("Div Event");
    }
    <div onclick="divEvent()">
        <input type="button" id="buttonId" value="showEvent"/>
    </div>

    キーボードイベント
    window.onload=function(){
         // 
         document.onkeydown=showkey;
    }
    
    function showkey(e){
         var key;
         if(window.event)
              key= window.event.keyCode;
         else
              key= e.keyCode;
    
         alert(String.fromCharCode(key));
    }

    マウスイベント
    mouseの場所の取得
    IE: clientX,clientY
    Other: pageX, pageY
    document.onmouseover= showPosition;