Professional JS(11.4.4-Markup Insertion/Scrolling/Event Flow/Event Handler/Event Object(part))

来源:互联网 发布:蓝光膜 知乎 编辑:程序博客网 时间:2024/03/29 17:38

1.Markup Insertion(插入标记)
①The innerText property works with all text content contained with an element,regardless of how deep in the subtree the text exists.When used to read the value,innerText concatenates the values of all text nodes in the subtree in depth-first order.When used to write the value,innerText removes all childeren of the element and inserts a text node containing the given value.

②Setting innerText removes all of the child nodes that exists before,completely changing the DOM subtree.Additionally,setting innerText encodes all HTML syntax characters(less-than,greater-than,quotation marks” and ampersands(&)) that may appear in the text.

+③The innerText property is supported in IE4+,Safari 3+,Opera 8+ and Chrome.Firefox does not support innerText,but it supports an equivalent property called textContent.The textContent property is specified in DOM Level 3 and is also supported by IE 9+,Safari 3+.Opera 10+ and Chrome.For cross-browser compability,it's helpful to use functions that check which property os available.

function getInnerText(element){    return (typeof element.textContent == 'string') ?         element.textContent : element.innerText;}function setInnerText(element,text){    if(typeof element.textContent=='string'){        element.textContent=text;    }else{        element.innerText=text;    }}//调用这两个函数setInnerText(div,'Hello yyc.');getInnerText(div);//"Hello yyc."

④There is a slight(轻微的) difference in the content returned from innerText and that returned from textContent.Whereas innerText skips(跳过) over inline style(行内样式) and script blocks,textContent returns any inline style or script code along with other text.The best way to avoid cross-browser differences are to use read text only on shallow(浅的) DOM subtrees or in parts of the DOM where there are no inline styles or inline scripts.

+⑤The outerText[不推荐使用] property works in the same way as innerText property except that it includes the node on which it's called(删得更加彻底).For reading text values,outerText and innerText essentially behave in the exact(完全的) same way.In writing mode,however,outerText behaves very differently,Instead of replacing just the child nodes of the element on which it's used,outerText actually replaces the entire element,including its child nodes.

div.outerText='Hello yyc.';//喧宾夺主var text=document.createTextNode('Hello yyc.');div.parentNode.replaceChild(text,div);

⑥The outerText property is supported by IE 4+,Safari 3+,Opera 8+ and Chrome.This property is typically not used since it modifies the element on which it is accessed.

2.Scrolling
①scrollIntoViewIfNeeded(alignCenter)—-Scrolls the browser window or container element so that the element is visible in the viewport only if it's not already visible;if the element is already visible in the viewport,this method does nothing.The optional alignCenter argument will attempt to place the element in the center of the viewport if set to true.This is implemented in Safari and Chrome.

②scrollByLines(lineCount)—-Scrolls the contents of the element by the height of the given number of text lines,which may be positive or negative(正负值).This is implemented in Safari and Chrome.

③scrollByPages(pageCount)—-Scrolls the contents of the element by the height of a page,which is determined by the height of the element.This is implemented in Safari and Chrome.

④Keep in mind that scrollIntoView() and scrollIntoViewIfNeeded() act on the element's container,whereas scrollByLines() and scrollByPages() affect the element itself.

3.Events
①JavaScript's interaction with HTML is handled through events,which indicate when particular moments of interest occur in the document or browser window.

②Events first appeared in IE 3 and Netscape Navigator 2 as a way to offload(分担) some form processing(表单处理) from the server onto the browser.

③When you click on a button,they concluded,you're clicking not just on the button but also on its container and on the page as a whole.

④Event flow(事件流) describes the order in which events are received on the page(页面接收事件的顺序),and interestingly,the IE and Netscape development teams came up with an almost exactly opposite concept of event flow.IE would support an event bubbling(冒泡) flow,whereas Netscape Communicator would support an event capturing flow(事件捕捉流).

4.Event Bubbling(由内到外)
①The IE event flow is called event bubbling,because an event is said to start at the most specific element(the deepest possible point in the document tree) and then flow upward toward the least specific node(the document).

②IE 5.5- skip bubbling to the <html> element(going from <body> directly to document).IE 9,Firefox,Chrome and Safari continue event bubbling up to the window object.

5.Event Capturing
①The theory of event capturing is that the least specific node(指向最模糊的节点,也就是最外层的节点) should receive the event first and the most specific node should receive the event last.【冒泡的逆】

②Although this was Netscape Communicator's only event flow model,event capturing is currently supported in IE9,【+4】.All of the them actually begin event capturing at the window-level event despite the fact that the DOM Level 2 Events specification indicates that the events should begin at document.

6.DOM Event Flow
①The event flow specified by DOM Level 2 Events has three phases(阶段):the event capturing phase,at the target,and the event bubbling phase.

*②In the DOM event flow,the actual target(the <div> element)does not receive the event during the capturing phase.This means that the capturing phase moves from document to<html> to<body> and stops.The next phase is “at target”,which fires on the <div> and is considered to be part of the bubbling phase in terms of(从…方面) event handling.Then,the bubbling phase occurs and the event travels back up to the document.

③Most of the browsers that support DOM event flow have implemented a quirk.Even though the DOM Level 2 Events specification indicates that the capturing phase doesn't hit the event target,IE 9,Opera 9.5+,【+3】all fire(触发) an event during the capturing phase on the event target.The end result is that there are two opportunities to work with the event on the target.

④IE 9,【+4】all support the DOM event flow;IE8- do not.

7.Event Handlers
①Events are certain(某个) actions performed either by the user or by the browser itself.These events have names like click,load and mouseover.A function that is called in reponse to an event is called an event hanlder(or an event listener).Event handlers have names beginning with “on”,so an event handler for the click event is called onclick and an event handler for the load event is called onload.Assigning event hanlders can be accomplished in a number of different ways.

8.HTML Event Handlers
①为了避免使用HTML实体,可以使用单引号替代双引号(需转义)。

+②Each event supported by a particular element can be assigned using an HTML attribute with the name of the event handler.

<input type='button' value='Click Me' onclick="alert('Clicked')"><input type='button' value='Click Me' onclick="alert(&quot;Clicked&quot;)">

③An event handler defined in HTML may contain the precise(明确的) action to take or it can call a script defined elsewhere on the page.Code executing as an event handler has access to everything in the global scope.

@@@@④Event handlers assigned in this way have some unique aspects.First,a function is created that wraps the attribute value.The function has a special local variable called event,which is the event object.
这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

⑤在HTML中指定事件处理程序的三个缺点:
a)存在时差。解决之法:try{showMessage();}catch(ex){}
b)事件处理程序生成的作用域链会在不同浏览器中导致不同的结果。
c)HTML和JS代码紧密耦合,如果要修改就要改两个地方。

9.DOM Level 0 Event Handlers
+①The traditional way to assigning event handlers in JavaScript is to assign a funciton to an event handler property.Note that the event hanlder isn't assigned until this code is run(在这些代码运行之前不会指定事件处理程序), so if the code appears after the code for the button in the page,there may be an amount of time during which the button will do nothing when clicked.(事件处理程序代码在button后面)。

//通过文档对象获得一个按钮的引用var btn=document.getElementById('myBtn');//为其指定onclick事件处理程序btn.onclick=function(){    alert('Clicked');}

②优点:简单/能跨浏览器。

@③When assigning event handlers using the DOM Level 0 method,the event handler is considered to be a method of the element.The event handler,therefore,is run within the scope of element,meaning that this is equivalent to the element.This code displays the element's ID when the button is clicked.The ID is retrieved using this.id.It's possible to use this to access any of the element's properties or methods from within the event handlers.Event handlers added in this way are intended for the bubbling phase of the event flow.
这里写图片描述

+④You can remove an event handler assigned via the DOM Level 0 approach by setting the value of the event handler property to null.

btn.onclick=null;//remove event handler

⑤If you've assigned an event handler using HTML,the value on the onclick property is a function containing the code specified in the HTML attribute.These event handlers can also be removed by setting the property to null.

10.DOM Level 2 Event Handler
+①DOM Level 2 Event define two methods to deal with the assignment and removal of event handlers:addEventListener() and removeEventListener().These methods exist on all DOM nodes and accepts three arguments:the event name to handle,the evet handler function, and a Boolean value indicating whether to call the event handler during the capture phase(捕获阶段)(true) or during the bubble phase(冒泡阶段)(false).

var btn=document.getElementById('myBtn');//要处理的事件名/作为事件处理程序的函数/布尔值btn.addEventListener('click',function(){    alert(this.id);},false);//false代表冒泡阶段触发

②As with the DOM Level 0 approach,the event handler runs in the scope of the element on which it is attached.

*③The major advantage to using the DOM Level 2 method for adding event handlers is that multiple event handlers can be added.适合批量生产

+④Event handlers added via addEventListener() can be removed only by using removeEventListener() and passing in the same arguments as were used when the handler was added.This means that anonymous(匿名的) functions added using addEventListener() cannot be removed.

var btn=document.getElementById('myBtn');btn.addEventListener('click',function(){    alert(this.id);},false);//删不掉,因为其添加的是匿名函数,移除时的第二个参数和添加时不同。btn.removeEventListener('click',function(){    alert(this.id);},false);//解决之道var btn=document.getElementById('myBtn');//将该函数保存在一个变量里面,变量真是个好东西var handler=function(){    alert(this.id);};btn.addEventListener('click',handler,false);btn.removeEventListener('click',handler,false);//移除成功

⑤In most case,event handlers are added to the bubbling phase of the event flow since this offers the broadest(最大限度的) possible cross-brower support(跨浏览器支持).

⑥DOM Level 2 event handlers are suppoted in IE 9,【+4】.

11.IE Event Handlers
+①IE implements(实现) methods similar to the DOM called attachEvent() and detachEvent().These methods accept the same two arguments:the event handler name and the event handler function.Since IE 8- support only event bubbling,event handlers added using attachEvent() are attached on the bubbling phase.

var btn=document.getElementById('myBtn'); //主要这里的第一个参数是onclick而不是clickbtn.attachEvent('onclick',function(){    alert('Clicked');});

+②A major difference between using attachEvent() and using the DOM Level 0 approach in IE is the scope of the event handler.When using DOM Level 0,the event handler runs with a this value equal to the element on which it is attached;when using attachEvent(),the event handler runs in the global context,so this is equivalent to window.

var btn=document.getElementById('myBtn');btn.attachEvent('onclick',function(){    alert(this===window);       //true});

+③The attachEvent() method,similar to addEventListener(),can be used to add multiple event handlers to a single element.But unlike the DOM method(addEventListener()),the event handlers fire(触发) in reverse of order they were added.

var btn=document.getElementById('myBtn');btn.addEventListener('onclick',function(){    alert('Clicked');},false);btn.addEventListener('onclick',function(){    alert('yyc');},false);//先返回"Clicked",再返回"yyc"/*------------------------*/var btn=document.getElementById('myBtn');btn.attachEvent('onclick',function(){    alert('Clicked');       //true});btn.attachEvent('onclick'function(){    alert('yyc');});//先返回"yyc",再返回"Clicked"

+④Events added using attachEvent() are removed using detachEvent() as long as the same arguments are provided.As with the DOM 2 methods(addEventListener(),removeEventListener()),this means that anonymous functions(匿名函数) cannot be removed once they have been added.

var btn=document.getElementById('myBtn');var handler=function(){    alert('yyc');};btn.attachEvent('onclick',handler);btn.detachEvent('onclick',handler);

⑤IE event handlers are supported in IE and Opera.

12.Cross-Browser Event Handlers
①The first method to create is called addHandler(),and its job is to use the DOM Level 0 approach,the DOM Level 2 approach,or the IE approach to adding events,depending on which is available.This method is attached to an obejct called EventUtil that will be used throughout this book to aid in handling cross-browser differences.The addHandler() method accepts three arguments:the element to act on,the name of the event, and the event handler function.

+②

//事件工具包var EventUtil={    addHandler:function(element,type,handler){        if(element.addEventListener){            element.addEventListener(type,handler,false);//DOM 2        }else if(element.attachEvent){            element.attachEvent('on'+type,handler);//IE        }else{            element['on'+type]=handler;//DOM 0        }    },    removeHandler:function(element,type,handler){        if(element.removeEventListener){            element.removeEventListener(type,handler,false);        }else(element.detachEvent){            element.detachEvent('on'+type,handler);        }else{            element['on'+type]=null;        }    }};var btn=document.getElementById('myBtn');var handler=function(){    alert('yyc');};EventUtil.addHandler(btn,'click',handler);//要操作的元素/事件名称/事件处理程序函数//...EventUtil.removeHandler(btn,'click',handler);//注意一点:DOM 0级对每个事件只支持一个事件处理程序

13.The Event Objecy
①When an event related to the DOM is fired,all of the relevant information is gathered and stored on an object called event.This object contains basic information such as the element that caused the event,the type of event that occured,and any other data that may be relevant to the particular event.For example,an event caused by a mouse action generates information about the mouse's position,whereas an event caused by a keyboard action generates information about the keys that were pressed.All browsers support the event object,though not in the same way.

14.The DOM Event Object
+@①Inside an event handler,the this object is always equal to the value of currentTarget,whereas target contains only the actual target of the event.

var btn=document.getElementById('myBtn');btn.onclick=function(event){    alert(event.currentTarget===this);//true    alert(event.target===this);//true};document.body.onclick=function(event){    alert(event.currentTarget===this);//true}

这里写图片描述

+②The type property is useful when you want to assign a single function to handle multiple events.

var btn=document.getElementById('myBtn');var handler=function(event){    switch(event.type){        case 'click':            alert('Clicked');            break;        case 'mouseover':        //注意是等号            event.target.style.backgroundColor='orange';            break;        case 'mouseout':            event.target.style.backgroundColor='';            break;    }};btn.onclick=handler;btn.mouseover=handler;btn.mouseout=handler;

③The preventDefault() method is used to prevent the default action of a particular event(比如阻止锚元素的导航行为).Any event that can be canceled using preventDefault() will have its cancelable property set to true.

原创粉丝点击