前端基础笔记

【javascript】事件类型

2017-12-14  本文已影响9人  shanruopeng

事件类型

//事件处理程序
var EventUtil = {
    addHandler: function(element, type, handler){
        if (element.addEventListener){
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent){
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    getEvent: function(event){
        return event ? event : window.event;
    },
    removeHandler: function(element, type, handler){
        if (element.removeEventListener){
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;
        }
    }
};

1、UI事件

(1)load事件

//第一种定义onload 事件处理程序的方式
EventUtil.addHandler(window, "load", function(event){
    alert("Loaded!");
});
<!--第二种指定onload 事件处理程序的方式-->
<!DOCTYPE html>
<html>
    <head>
        <title>Load Event Example</title>
    </head>
    <body onload="alert('Loaded!')">
    </body>
</html>

(2)unload事件

EventUtil.addHandler(window, "unload", function(event){
    alert("Unloaded");
});
<!DOCTYPE html>
<html>
    <head>
        <title>Unload Event Example</title>
    </head>
    <body onunload="alert('Unloaded!')">
    </body>
</html>

(3)resize事件

EventUtil.addHandler(window, "resize", function(event){
    alert("Resized");
});

(4)scroll事件

EventUtil.addHandler(window, "scroll", function(event){
    if (document.compatMode == "CSS1Compat"){
        alert(document.documentElement.scrollTop);
    } else {
        alert(document.body.scrollTop);
    }
});

(5)abort

(6)error

(7)select

2、焦点事件

var isSupported = document.implementation.hasFeature("FocusEvent", "3.0");

3、鼠标与滚轮事件

var isSupported = document.implementation.hasFeature("MouseEvent", "3.0")

(1)客户区坐标位置

var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "click", function(event){
    event = EventUtil.getEvent(event);
    alert("Client coordinates: " + event.clientX + "," + event.clientY);
});

(2)页面坐标位置

var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "click", function(event){
    event = EventUtil.getEvent(event);
    alert("Page coordinates: " + event.pageX + "," + event.pageY);
});
var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "click", function(event){
    event = EventUtil.getEvent(event);
    var pageX = event.pageX,
    pageY = event.pageY;
    if (pageX === undefined){
        pageX = event.clientX + (document.body.scrollLeft ||
        document.documentElement.scrollLeft);
    }
    if (pageY === undefined){
        pageY = event.clientY + (document.body.scrollTop ||
        document.documentElement.scrollTop);
    }
    alert("Page coordinates: " + pageX + "," + pageY);
});

(3)屏幕坐标位置

var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "click", function(event){
    event = EventUtil.getEvent(event);
    alert("Screen coordinates: " + event.screenX + "," + event.screenY);
});

(4)修改键

var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "click", function(event){
    event = EventUtil.getEvent(event);
    var keys = new Array();
    if (event.shiftKey){
        keys.push("shift");
    }
    if (event.ctrlKey){
        keys.push("ctrl");
    }
    if (event.altKey){
        keys.push("alt");
    }
    if (event.metaKey){
        keys.push("meta");
    }
    alert("Keys: " + keys.join(","));
});

(5)相关元素

<!DOCTYPE html>
<html>
    <head>
    <title>Related Elements Example</title>
    </head>
    <body>
        <div id="myDiv" style="background-color:red;">test</div>
    </body>
</html>
var EventUtil = {
//省略了其他代码
    getRelatedTarget: function(event){
        if (event.relatedTarget){
            return event.relatedTarget;
        } else if (event.toElement){
            return event.toElement;
        } else if (event.fromElement){
            return event.fromElement;
        } else {
            return null;
        }
    },
//省略了其他代码
};

var div = document.getElementById("myDiv");
EventUtil.addHandler(div, "mouseout", function(event){
    event = EventUtil.getEvent(event);
    var target = EventUtil.getTarget(event);
    var relatedTarget = EventUtil.getRelatedTarget(event);
    alert("Moused out of " + target.tagName + " to " + relatedTarget.tagName);
});

(6)鼠标按钮

var EventUtil = {
    //省略了其他代码
    getButton: function(event){
        if (document.implementation.hasFeature("MouseEvents", "2.0")){
            return event.button;
        } else {
            switch(event.button){
            case 0:
            case 1:
            case 3:
            case 5:
            case 7:
                return 0;
            case 2:
            case 6:
                return 2;
            case 4:
                return 1;
            }
        }
    },
    //省略了其他代码
};
var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "mousedown", function(event){
    event = EventUtil.getEvent(event);
    alert(EventUtil.getButton(event));
});

(7)鼠标滚轮事件

EventUtil.addHandler(document, "mousewheel", function(event){
    event = EventUtil.getEvent(event);
    alert(event.wheelDelta);
});

(8)触摸设备

4、键盘与文本事件

(1)键码

var textbox = document.getElementById("myText");
EventUtil.addHandler(textbox, "keyup", function(event){
    event = EventUtil.getEvent(event);
    alert(event.keyCode);
});

(2)字符编码

//跨浏览器取得字符编码
var EventUtil = {
    //省略的代码
    getCharCode: function(event){
        if (typeof event.charCode == "number"){
            return event.charCode;
        } else {
            return event.keyCode;
        }
    },
    //省略的代码
};
var textbox = document.getElementById("myText");
EventUtil.addHandler(textbox, "keypress", function(event){
    event = EventUtil.getEvent(event);
    alert(EventUtil.getCharCode(event));
});

(3)DOM3级变化

var textbox = document.getElementById("myText");
EventUtil.addHandler(textbox, "keypress", function(event){
    event = EventUtil.getEvent(event);
    var identifier = event.key || event.keyIdentifier;
    if (identifier){
        alert(identifi er);
    }
});

(4)textInput事件

var textbox = document.getElementById("myText");
EventUtil.addHandler(textbox, "textInput", function(event){
    event = EventUtil.getEvent(event);
    alert(event.data);
});

5、复合事件

var textbox = document.getElementById("myText");
EventUtil.addHandler(textbox, "compositionstart", function(event){
    event = EventUtil.getEvent(event);
    alert(event.data);
});
EventUtil.addHandler(textbox, "compositionupdate", function(event){
    event = EventUtil.getEvent(event);
    alert(event.data);
});
EventUtil.addHandler(textbox, "compositionend", function(event){
    event = EventUtil.getEvent(event);
    alert(event.data);
});
var isSupported = document.implementation.hasFeature("CompositionEvent", "3.0");

6、变动事件

<! DOCTYPE html>
<html>
    <head>
        <title>Node Removal Events Example</title>
    </head>
    <body>
        <ul id="myList">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </body>
</html>

(1)删除节点

//假设要移除<ul>元素,验证以上事件发生的顺序。
EventUtil.addHandler(window, "load", function(event){
    var list = document.getElementById("myList");
    EventUtil.addHandler(document, "DOMSubtreeModified", function(event){
        alert(event.type);
        alert(event.target);
    });
    EventUtil.addHandler(document, "DOMNodeRemoved", function(event){
        alert(event.type);
        alert(event.target);
        alert(event.relatedNode);
    });
    EventUtil.addHandler(list.firstChild, "DOMNodeRemovedFromDocument", 
    function(event){
        alert(event.type);
        alert(event.target);
    });
    list.parentNode.removeChild(list);
});

(2)插入节点

//假设要为<ul>添加一个<li>元素,验证以上事件发生的顺序。
EventUtil.addHandler(window, "load", function(event){
    var list = document.getElementById("myList");
    var item = document.createElement("li");
    item.appendChild(document.createTextNode("Item 4"));
    EventUtil.addHandler(document, "DOMSubtreeModified", function(event){
        alert(event.type);
        alert(event.target);
    });
    EventUtil.addHandler(document, "DOMNodeInserted", function(event){
        alert(event.type);
        alert(event.target);
        alert(event.relatedNode);
    });
    EventUtil.addHandler(item, "DOMNodeInsertedIntoDocument", function(event){
        alert(event.type);
        alert(event.target);
    });
    list.appendChild(item);
});

7、HTML5事件

(1)contextmenu事件

<!DOCTYPE html>
<html>
    <head>
        <title>ContextMenu Event Example</title>
    </head>
    <body>
        <div id="myDiv">Right click or Ctrl+click me to get a custom context menu.Click anywhere else to get the default context menu.</div>
        <ul id="myMenu" style="position:absolute;visibility:hidden;
        background-color:silver">
            <li><a href="http://www.nczonline.net">Nicholas’ site</a></li>
            <li><a href="http://www.wrox.com">Wrox site</a></li>
            <li><a href="http://www.yahoo.com">Yahoo!</a></li>
        </ul>
    </body>
</html>
EventUtil.addHandler(window, "load", function(event){
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "contextmenu", function(event){
        event = EventUtil.getEvent(event);
        EventUtil.preventDefault(event);
        var menu = document.getElementById("myMenu");
        menu.style.left = event.clientX + "px";
        menu.style.top = event.clientY + "px";
        menu.style.visibility = "visible";
    });
    EventUtil.addHandler(document, "click", function(event){
        document.getElementById("myMenu").style.visibility = "hidden";
    });
});

(2)beforeunload事件

EventUtil.addHandler(window, "beforeunload", function(event){
    event = EventUtil.getEvent(event);
    var message = "I'm really going to miss you if you go.";
    event.returnValue = message;
    return message;
});

(3)DOMCdontentLoaded事件

EventUtil.addHandler(document, "DOMContentLoaded", function(event){
    alert("Content loaded");
});

(4)hashchange事件

EventUtil.addHandler(window, "hashchange", function(event){
    alert("Old URL: " + event.oldURL + "\nNew URL: " + event.newURL);
});
EventUtil.addHandler(window, "hashchange", function(event){
    alert("Current hash: " + location.hash);
});
var isSupported = ("onhashchange" in window) && (document.documentMode ===
undefined || document.documentMode > 7);

8、设备事件

(1)orientationchange事件

EventUtil.addHandler(window, "load", function(event){
    var div = document.getElementById("myDiv");
    div.innerHTML = "Current orientation is " + window.orientation;
    EventUtil.addHandler(window, "orientationchange", function(event){
        div.innerHTML = "Current orientation is " + window.orientation;
    });
});

(2)MozOrientation 事件

EventUtil.addHandler(window, "MozOrientation", function(event){
    //响应事件
});

Warning: This experimental API was removed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), when support for the standard DeviceOrientationEvent was implemented. You should use that API instead.

(3)deviceorientation 事件

EventUtil.addHandler(window, "deviceorientation", function(event){
    var output = document.getElementById("output");
    output.innerHTML = "Alpha=" + event.alpha + ", Beta=" + event.beta +
    ", Gamma=" + event.gamma + "<br>";
});
EventUtil.addHandler(window, "deviceorientation", function(event){
var arrow = document.getElementById("arrow");
    arrow.style.webkitTransform = "rotate(" + Math.round(event.alpha) + "deg)";
});

(4)devicemotion 事件

EventUtil.addHandler(window, "devicemotion", function(event){
    var output = document.getElementById("output");
    if (event.rotationRate !== null){
        output.innerHTML += "Alpha=" + event.rotationRate.alpha + ", Beta=" +
        event.rotationRate.beta + ", Gamma=" +
        event.rotationRate.gamma;
    }
});

9、触摸与手势事件

(1)触摸事件

名称 详细
touchstart 当手指触摸屏幕时触发;即使已经有一个手指放在了屏幕上也会触发。
touchmove 当手指在屏幕上滑动时连续地触发。在这个事件发生期间,调用preventDefault()可以阻止滚动。
touchend 当手指从屏幕上移开时触发。
touchcancel 当系统停止跟踪触摸时触发。
function handleTouchEvent(event){
//只跟踪一次触摸
    if (event.touches.length == 1){
    var output = document.getElementById("output");
    switch(event.type){
        case "touchstart":
            output.innerHTML = "Touch started (" + event.touches[0].clientX +
            "," + event.touches[0].clientY + ")";
            break;
        case "touchend":
            output.innerHTML += "<br>Touch ended (" +
            event.changedTouches[0].clientX + "," +
            event.changedTouches[0].clientY + ")";
            break;
        case "touchmove":
            event.preventDefault(); //阻止滚动
            output.innerHTML += "<br>Touch moved (" +
            event.changedTouches[0].clientX + "," +
            event.changedTouches[0].clientY + ")";
            break;
        }
    }
}
EventUtil.addHandler(document, "touchstart", handleTouchEvent);
EventUtil.addHandler(document, "touchend", handleTouchEvent);
EventUtil.addHandler(document, "touchmove", handleTouchEvent);

(2)手势事件

名称 详细
gesturestart 当一个手指已经按在屏幕上而另一个手指又触摸屏幕时触发。
gesturechange 当触摸屏幕的任何一个手指的位置发生变化时触发。
gestureend 当任何一个手指从屏幕上面移开时触发。
名称 详细
rotation 表示手指变化引起的旋转角度,负值表示逆时针旋转,正值表示顺时针旋转(该值从0 开始)。
scale 表示两个手指间距离的变化情况(例如向内收缩会缩短距离);这个值从1 开始,并随距离拉大而增长,随距离缩短而减小。
function handleGestureEvent(event){
    var output = document.getElementById("output");
    switch(event.type){
    case "gesturestart":
        output.innerHTML = "Gesture started (rotation=" + event.rotation +
        ",scale=" + event.scale + ")";
        break;
    case "gestureend":
        output.innerHTML += "<br>Gesture ended (rotation=" + event.rotation +
        ",scale=" + event.scale + ")";
        break;
    case "gesturechange":
        output.innerHTML += "<br>Gesture changed (rotation=" + event.rotation +
        ",scale=" + event.scale + ")";
        break;
    }
}
document.addEventListener("gesturestart", handleGestureEvent, false);
document.addEventListener("gestureend", handleGestureEvent, false);
document.addEventListener("gesturechange", handleGestureEvent, false);
好好学习
上一篇下一篇

猜你喜欢

热点阅读