Events Handling(事件处理) -- 编辑中
事件处理要解决的问题:为什么要监听事件,要监听什么事件,监听到要做什么及如何做.
事件类型(解决要监听什么事件)
如何监听事件
监听前
Registering Event Handlers(注册事件处理器)
Two ways:
- Setting a property on the object or document element that is the event target.
1.1 Setting Event Handler Properties
// Set the onload property of the Window object to a function.// The function is the event handler: it is invoked when the document loads.window.onload =function() {// Look up a <form> elementvarelt = document.getElementById("shipping_address");// Register an event handler function that will be invoked right// before the form is submitted.elt.onsubmit =function() {returnvalidate(this);}}Shortcoming:
Designed around the assumption that event targets will have at most one handler for each type of event. If you are writing library code for use in arbitrary documents, using this technique maybe modify or overwrite the previously registered handlers.
1.2 Setting Event Handler Attributes
<buttononclick="alert('Thank you');">Click Here</button>Pls remember:
1)The attribute value should be a string of JavaScript code. That code should be the body of the event handler function, not a complete function declaration(即attributes的值应只是事件处理函数的主体,无需函数的完整定义).That is, your HTML event handler code should not be surrounded by curly braces and prefixed with the function keyword.
2)If an HTML event handler attribute contains multiple JavaScript statements, you must remember to separate those statements with semicolons(分号) or to break the attribute value across multiple lines(断开属性值使其跨多行).
Pls know:
1)Some event types are directed at the browser as a whole, rather than at any particular document element(即全局事件).The following is the complete list of such event handlers as defined by the draft HTML5 specification:
onafterprint onfocus ononline onresizeonbeforeprint onhashchange onpagehide onstorageonbeforeunload onload onpageshow onundoonblur onmessage onpopstate onunloadonerror onoffline onredo2)When you specify a string of JavaScript code as the value of an HTML event handler attribute, the browser converts your string into a function that looks something like this(Event Handler Attributes的事件触发工作原理):
function(event) {with(document) {with(this.form || {}) {with(this) {/* your code here */}}}}Shortcoming:
Directly mix JavaScript and HTML. A common style in client-side programming involves keeping HTML content separate from JavaScript behavior. So Programmers who follow this discipline should avoid using this technique.
 - 
Passing the handler to a method of the object or element.
2.1 AddEventListener()<buttonid="mybutton">Click me</button><script>var b = document.getElementById("mybutton");b.onclick = function() { alert("Thanks for clicking me!"); };b.addEventListener("click", function(){ alert("Thanks again!"); }, false);</script>addEventListener():(介绍函数参数及作用) Takes three arguments.The first is the event type for which the handler is being registered. The second argument to addEventListener() is the function that should be invoked when the specified type of event occurs.The final argument to addEventListener() is a boolean value.Normally, you’ll pass false for this argument. If you pass true instead, your function is registered as a capturing event handler and is invoked at a different phase of event dispatch.Ought be able to omit the third argument instead of passing false, and the specification may eventually change to allow this, but for now, omitting that argument is an error in some current browsers.
removeEventListener(): paired with addEventListener() that expects the same three arguments but removes an event handler function from an object rather than adding it.
document.removeEventListener("mousemove", handleMouseMove,true);document.removeEventListener("mouseup", handleMouseUp,true);Advantages: Newer and more general event handler technique
Shortcoming: IE8 and earlier don't support this technique.
2.2 attachEvent()
attachEvent() and detachEvent() work like addEventListener() and removeEventListener(), with the following exceptions(介绍attachEvent和addEventListener的不同之处):
1)(不支持事件捕捉,故只有两个参数)Since the IE event model does not support event capturing, attachEvent() and detachEvent() expect only two arguments: the event type and the handler function.
2)(event handler property name 带 on 前缀)The first argument to the IE methods is an event handler property name, with the “on” prefix, rather than the unprefixed event type. For example, pass “onclick” to attachEvent() where you would pass “click” to addEventListener().
3)(相同的事件处理函数可被多次注册,特定事件类型发生时,注册函数调用次数和注册次数一样)attachEvent() allows the same event handler function to be registered more than once. When an event of the specified type occurs, the registered function will be invoked as many times as it was registered.(注册事件函数的标准做法)It is common to see event handler registration code that uses addEventListener() in browsers that support it and otherwise uses attachEvent():
varb = document.getElementById("mybutton");varhandler =function() { alert("Thanks!"); };if(b.addEventListener)b.addEventListener("click", handler,false);elseif(b.attachEvent)b.attachEvent("onclick", handler); 
监听到事件之后
Event Handler Invocation(调用事件处理器/程序)
Event Handler(事件处理函数):
1)如何获得事件源信息:the event handler argument,即参数;
2)获得事件源信息后如何处理:the invocation context (the "this" value), the invocation scope;
3)处理后的返回结果:the meaning of the return value.
4)浏览器的兼容性情况(IE8.0及以前和其他的区别)
Events Propagate(事件传播):How a single event can trigger the invocation of multiple handlers on the original event target and also on containing elements of the document(即单个触发事件如何引发其他相关事件)
1.Event Handler
1.1 Event Handler Argument
考虑浏览器兼容性(主要是兼容IE8.0及以前)的代码:
function handler(event) {      event = event || window.event;      // Handler code goes here                } | 
Coding Reason: In IE8 and before, event handlers registered may be not passed an event object when they are invoked. Instead, the event object is available through the global variable window.event. So for portability, you can write event handlers like this, so that they use the window.event if no argument is supplied.
1.2 Event Handler Context
考虑浏览器兼容性(主要是兼容IE8.0及以前)的代码:
Coding Shortcomings:(事件处理函数注册后无法移除)event handlers registered using this method cannot be removed, since the wrapper function passed to attachEvent() is not retained anywhere to be passed to detachEvent().
1.3 Event Handler Scope
1.4 Handler Return Value
1.5 Invocation Order(调用次序)
When an appropriate event occurs, the browser must
invoke all of the handlers, following these rules of invocation order:
•(The object property or HTML attribute 注册的事件处理函数先调用)Handlers registered by setting an object property or HTML attribute, if any, are
always invoked first.
• (addEventListener 注册的事件处理函数按注册顺序调用)Handlers registered with addEventListener() are invoked in the order in which
they were registered.
• (attachEvent()乱序调用)Handlers registered with attachEvent() may be invoked in any order and your code
should not depend on sequential invocation.
1.6 Event Propagation(事件传播)
Three phase of event propagation(事件传播三阶段):Event capturing(if supported and necessary) -> Invocation of the event handlers of the target object -> Event bubbling(for most events)
Event bubbling(事件冒泡):
Define:(DOM tree中的大部分事件会在事件源element调用事件处理函数后,不断被往上扔(冒泡)直至DOM 树根:window object)
After the event handlers registered on the target element are invoked, most events
“bubble” up the DOM tree. The event handlers of the target’s parent are invoked. Then
the handlers registered on the target’s grandparent are invoked. This continues up to
the Document object, and then beyond to the Window object.
Advantage:(若子节点有相同或相似的事件处理函数,可以在共同的父节点处设置一个事件处理函数来处理各子节点的事件触发)provides an alternative to registering handlers on lots of individual document elements: instead you can register a single handler on a common ancestor element and handle events there.eg.You might register an “change” handler on a <form> element, for example, instead of registering a “change” handler for every element in the form.
Exceptions:
1)focus, blur, and scroll events don't have
2)The load event on document elements bubbles, but it stops bubbling at the Document object and does not propagate on to the Window object.The load event of the Window object is triggered only when the entire document has loaded.
Event capturing(事件捕获)
Define:(event bubbling的逆过程,不同之处在于目标事件本身的事件处理函数不会被调用)it is like the event bubbling in reverse. The capturing handlers of the Window object are invoked first, then the capturing handlers of the Document object, then of the body object, and so on down the DOM tree until the capturing event handlers of the parent of the event target are invoked. Capturing event handlers registered on the event target itself are not invoked.
Advantages:Provides an opportunity to peek at events before they are delivered to their target.
常用场景:
1)debugging
2)Be used along with the event cancellation technique to filter events so that the target event handlers are never actually invoked.
Shortcomings:Only works with event handlers registered with addEventListener() when the third argument is true.So IE8.0 and before are not supported.
1.7 Event Cancellation
Two kind of common Event Cancellation(2种常见的事件取消类型):
1.7.1 Browser’s default action of the event cancellation
考虑浏览器兼容性(兼容IE8.0及以前)的代码:
function cancelHandler(event) { var event = event || window.event;  // For IE         /* Do something to handle the event here */         // Now cancel the default action associated with the event    if(event.preventDefault) event.preventDefault();  // Standard technique    if(event.returnValue) event.returnValue = false;  // IE8.0 and before     return false;  // For handlers registered as object properties     } | 
Coding Reason:
For event handlers registered as properties, the return value setted as false can
be used to cancel the browser’s default action for the event. In browsers that support
addEventListener(), you can also cancel the default action for an event by invoking the
preventDefault() method of the event object. In IE prior to IE9, however, you do the
same by setting the returnValue property of the event object to false.
More:
The current DOM Events module draft defines a property of the Event object named
defaultPrevented. It is not yet widely supported, but the intent is that this property will
normally be false but will become true if preventDefault() is called.
(The jQuery event object has a defaultPrevented() method instead of a property.)
1.7.2 Event propagation cancellation
In the browser other than IE8.0 and before(support
addEventListener()):
stopPropagation(): (可在事件传播的任意阶段--事件捕捉,事件目标本身及事件冒泡阶段--调用这一事件方法用以阻止事件继续传播,调用后同一对象的其他事件处理函数将依旧被调用,但任何其他对象上的事件处理函数将不被调用.)you can
invoke this event method to prevent the continued propagation of the event. If there are other handlers
defined on the same object, the rest of those handlers will still be invoked, but no event
handlers on any other object will be invoked after stopPropagation() is called. The
stopPropagation() method can be called at any time during event propagation. It works
during the capturing phase, at the event target itself, and during the bubbling phase.
stopImmediatePropagation(): (类似stopPropagation(),但调用后同一对象的其他事件处理函数将不被继续调用)method defined by the current draft DOM Events specification.
Like stopPropagation(), this method prevents the propagation of the event to any other objects. But it also prevents the invocation of any other event handlers registered on the same object. For now, some browsers support stopImmediatePropagation() and some do not. Some
utility libraries, like jQuery and YUI, define stopImmediatePropagation() in a cross-platform way.
IE8 and before:
cancelBubble:
IE does not support the stopPropagation() method. Instead, the IE event
object has a property named cancelBubble. Set this property to true to prevent any further propagation. (IE8 and before do not support the capturing phase of event prop-agation, so bubbling is the only kind of propagation to be canceled.)
具体事件类型编码
Document Load Events
考虑浏览器兼容性(兼容IE8.0及以前)的代码:
whenReady.js
Coding Reason: To be continued...
Mouse Events
Mouse Drag(鼠标拖动) Example
考虑浏览器兼容性(兼容IE8.0及以前)的代码:
Drag.js:
How to use drag() in an HTML file Code:
The key here is the onmousedown attribute of the inner <div> element. Note that it uses this.parentNode to specify that the entire container element is to be dragged.
Coding Reason for Drag.js : To be continued...
Mousewheel Events(鼠标滚轮事件)
考虑浏览器兼容性的代码:
Enclose.js:
How to use drag() in an HTML file Code:
Reminder for Enclose.js:
In order to work correctly in all common browsers, Enclose.js must perform some browser testing(which can be find in the book(English version) page 472 & chapter 13.4.5 Browser Testing). Enclose.js anticipates the DOM Level 3 Events specification and includes code to use the wheel event when browsers implement it(This is risky: if future implementations do not match the draft specification current as I write this, this will backfire and the example will break.).It also includes some future-proofing to stop using the DOMMouseScroll event when Firefox starts firing wheel or mousewheel. It is also a practical example of the element geometry and CSS positioning techniques.
Coding Reason for Enclose.js:To be continued...
Drag and Drop Events
To be continued...
Text Events
考虑浏览器兼容性的代码:
InputFilter.js:功能为过滤字符,当输入框输入不符合条件的字符时,会弹出相应的错误提示.
How to use InputFilter.js in an HTML file Code:
eg.
<input id="zip" type="text" data-allowed-chars="0123456789" data-messageid="zipwarn"><span id="zipwarn" style="color:red;visibility:hidden">Digits only</span> | 
Coding Reason for InputFilter.js: To be continued...
posted on 2013-07-10 18:11 chhruichhrui 阅读(274) 评论(0) 收藏 举报
                    
                
                
            
        
浙公网安备 33010602011771号