添加事件
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;