DOM

Document Object Model, which gets elements from the browser-provided Document Object.

The event

Events are specific moments of interaction that occur in a document or browser window.

The interaction between javascript and HTML is achieved through events.

For Web applications, these are typical events: clicking on an element, moving the mouse over an element, pressing a case on the keyboard, and so on.

Example: Bind an event to a button

var btn=document.getElementById('btn');
btn.onclick=function(){};
Copy the code

The event function code should be written after the element, because all code is executed line by line. The event function needs to fetch the element first, but it cannot fetch the element before the HTML element is created.

You can put the event function code in the window.onload() method because the onload method is executed when the page has finished loading.

Writing last is the most efficient and best user experience.

Special event

Wheel events

  • onmousewheelNot available in Firefox
  • Elements. The addEventListener (" DOMMouseScroll ", fun, false);This method must be used in Firefox, and the event string must beDOMMouseScroll

Method to get an element node

methods describe
getElementById() By IDTo obtainOne of the elements
getElementsByTagName() Gets a set of elements by tag name
getElementsByName() throughnameProperty gets a set of elements
getElementsByClassName() throughclassProperty gets a set of elements,IE9The following is not supported
querySelector() throughCSSThe selector gets the first element that meets the requirement and can be inIE8The use of
querySelectorAll() Same as above, but all elements that meet the criteria are retrieved

Gets element child nodes and child elements

methods describe
el.childNodes This property gets all nodes including text nodes (HTMLSpaces between codes), notice, inIE8Blank text is not treated as a child node
el.children Gets all child elements, excluding text nodes
el.firstchild Gets the first child node of the element
el.lastchild Gets the last child node of the element
el.firstElemetChild Gets the first child of the element,IE8And the following are not supported

Gets the parent and sibling nodes of the element

methods describe
el.parentNode Gets the parent node of the element
el.previousSibling Represents the previous sibling of the current node, possibly with a space
el.nextSibling Represents the next sibling of the current node, possibly with a space

Getting element content

methods describe
el.innerHTML Gets the inside of the element tagHTMLCode (including child element tags)
el.innerText Gets the text content inside the element tag (excluding child element tags)

Special acquisition method

methods describe
document.body To obtainbodyObject, you can usegetElementByAnd so on, butdocumentBuilt into thebodyProperty preservationbodyobject
document.documentElement To obtainHTMLobject
document.all Gets all elements of type and valueundefinedBut it can be accessed, maybebug
document.getElementByTagName("*") Get all elements

Add elements

  1. Create the element

    Var ele = document.createElement(' createElement ')

  2. Create a bittext node and append

    var txt = document.createTextNode()

    ele.appendChild(txt)

Add the position

AppendChild ()// Take the return value of the newly created element as an argumentParent object. InsertBefore (new object, specifying children)// Insert a new child node before the specified child nodeParent object. ReplaceChild (old, new)// Replace the child node
Copy the code

Remove elements

RemoveChild (child node)// The parent and child points need to be obtained in advanceParentnode.removechild (child node)// Do not need to get the parent node in advance
Copy the code

Modifying element styles

grammar

Style. Style name = style value;// If the style value is pixel, then "px" should be added at the end.
// If the style name is border-top-width, you need to change it to "borderTopWidth" with the camel name
Copy the code

The style to be modified is inline and has the highest precedence. It will take effect directly, but if the CSS has written! Important, then JS cannot override this style, so try not to use it! important

Styles read by style are also inline, so styles written by CSS are not read

Get element style

  • Gets an inline style

    • Element. Style. style name
  • Get the current displayed style (read only)

    • Element. CurrentStyle. Style name

      Only Internet Explorer is supported

      Some style values that default to auto will return auto, not the actual value

    • GetComputedStyle (element, pseudo-element)

      Other browsers and IE9 and above support that pseudo-elements generally pass null values

      Returns an object, accessed through the object

      Will actually return the value of the style

Integration compatibility issues

function getStyle(obj,name){
	if(window.getComputedStyle)
		return getComputedStyle(obj,null)[name];
	else
		return obj.currentStyle[name];
	// Or combine the above into a ternary expression? :
}
Copy the code

Other style properties

  • clientWidth/clientHeight

    • Gets the visible width/height of the element, returned withoutpx, can be directly calculated, read-only
    • Includes content area and inside margins, excluding borders
  • offsetWidth/offsetHeight

    • Gets the entire width/height of the element, withoutpx, can be directly calculated, read-only
    • Includes content areas and inside margins, including borders
  • offsetParent

    • Gets the ancestor element closest to the current element that opens the location
  • offsetLeft/offsetTop

    • Gets the horizontal/vertical offset of the current element relative to its positioned parent
  • scrollWidth/scrollHeight

    • Gets the width/height of the entire element scroll area
  • scrollLeft/scrollTop

    • Gets the scrolling distance of the horizontal/vertical scroll bar
    • If meetscrollHeight/scrollWidth-scrollTop/scrollLeft == clientHeight/clientWidth, it indicates that the scroll bar in this direction has reached the bottom

The event

The event object

When the response function to an event is fired, the browser passes an event object as an argument to the response function each time (IE8 and below do not pass this).

The event object encapsulates all information related to the current event, such as: the coordinates of the mouse keyboard which key was pressed to scroll the mouse wheel direction

In IE8 and below, event objects are saved as properties of window objects

General writing

Parameter = event | | window. The event;

Element setCapture() will forcibly transfer the next mouse click to itself, only once, IE8 does not work

Element releaseCapture() releases the capture, IE8 is not valid

The bubbling of events

When an event of a descendant element is triggered, the same event of its ancestor element is also triggered.

Example: Clicking on a SPAN within a div will trigger not only the span click event, but also the div click event (if it exists)

Bubbling of events is useful in development.

If you do not want bubbling to occur, you can cancel bubbling through the event object.

event.cancelBubble=true; Event. StopPropagation ();// All browsers support it
Copy the code

Delegate to events

The binding of events to an element’s ancestor so that when an event is triggered on a descendant element, it bubbles all the way to the ancestor element, thus processing the event through the ancestor element’s response function.

Event delegation is the use of bubbling, through delegation can reduce the number of event binding, improve the efficiency of the program.

Because events are bound to ancestor elements, they can be bound to unnecessary descendant elements, so you can determine within an event which element triggered the event by the target attribute of the event object.

Ancestor element. Onclick =function(e){
    e=event||window.event;
    if(e.target.className=='Classes you need to trigger') {/* Event execution code */}}Copy the code

Addition of multiple events

Disadvantages of the common method of binding events

Elements. The onclick =function(){};
// This method can bind only one function of one event to the element
// To bind multiple events, use, addEventListener()
Copy the code

addEventListener()

You can also bind response functions to elements using this method.

parameter

  1. Event string, noon
  2. A callback function that is fired when an event is fired
  3. Whether to fire the event during the capture phase requires a Boolean valuefalse
Elements. The addEventListener ("click".function(){
/* Event execution code */
},false);
/* This is the binding element */
Copy the code

The order of execution is the same as the order of addition

This is not supported in IE8, which uses attachEvent()

AttachEvent () support IE5-10

parameter

  1. Event string toon
  2. The callback function
Elements. AttachEvent ("onclick".function(){
/* Event execution code */
});
/* Where this isCopy the code

The order of execution is reversed from the order of addition

If both of the above must struggle with the order of execution, write the code in one event

Compatible with both methods

function bind(obj,eventStr,callBack){
	// Parameters: binding element object, event string (not on), callback function
	if(obj.addEventListener){
		obj.addEventListener(evenStr,callBack,false);
	}
	else{
		obj.attachEvent("on"+evenStr,function(){ callBack.call(obj); }}Copy the code

Transmission of events

Microsoft believes that the propagation of events is from inside out, first triggering the event of the current element, and then triggering the event of the ancestor element up and out, that is, the bubbling stage triggering event.

Netscape thinks of it as an outside-in process, first triggering the events of the ancestor element and then downward and inward triggering the events of the current element, which is the capture phase of the event.

The W3C combines the two companies’ proposals and divides event propagation into three phases

  1. Capture phase

    In this phase, events are captured from the outermost ancestor element to the target, but by default events are not fired at this time

  2. The target stage

    When the event catches the target element, the capture ends and events begin to fire on the target element

  3. Bubbling phase

    Events propagate from the target element outward to the ancestor element, firing events in turn

If you want the event to be executed during the capture phase, change the third parameter of addListener to true. In general, we do not want the capture phase to trigger, so it is generally false.

There is no capture phase in IE8 and below.

BOM

Browser Object Model Browser Object Model

BOM allows us to provide a set of objects that we can use to perform operations on the browser

BOM object

window

Represents the entire browser window, and window is also the global object of the web page.

Navigator

Represents information about the current browser, which allows you to identify different browsers.

For historical reasons, most of the properties in the Navigator object no longer help us identify the browser.

Generally, we only use the userAgent attribute to determine the browser information. This attribute is a string containing content that describes the browser information. Different browsers have different UserAgents.

Recognize browser mode

var ua=navigator.userAgent;
if(/firefox/i.test(ua)){
	alert("This is Firefox");
}else if(/chrome/i.test(ua)){
	alert("It's Chrome");
}else if(/msie/i.test(ua)){// Internet Explorer 11 removes the identifiers associated with IE
	alert("This is IE10 and below.");
}else if("ActiveXObject" in window){
	alert("You are Internet Explorer 11, where else to hide!");
}
/* If the userAgent is not able to determine, you can determine by some browser-specific objects */
/* For example, ActiveXObject*/ 
/* Crafty IE11 converts this property to a Boolean value of false, so it uses in to determine if the property exists */
Copy the code

Location

Represents the address bar information of the current browser. You can obtain the address bar information through Location or jump to the browser.

By printing location, you get the information (the full path to the current page) directly to the address bar.

If you change the location property directly to a full path or relative address, the page jumps to that path and the corresponding history is generated.

The object attribute of Location is to separate the entire path of the current address bar into properties. See the W3C reference manual for details.

  • assign( string )
    • Used to jump to other pages, and direct modificationlocationRole as
  • reload( [bool] )
    • As a refresh, the page cache still exists and the parameters are passedtrueIs forced to clear the cache and refresh the page
  • replace()
    • You can use a new page to replace the current page, the call will also jump to the page, different fromassign()Method, which does not generate history and therefore cannot move forward or backward

History

Represents browser history. You can use this object to manipulate browser history

For privacy reasons, the object cannot obtain specific historical records and can only be used to scroll forward or backward on the browser. This operation is valid only for the second access

  • length
    • Can get the number of links accessed at the time
  • back()
    • Equivalent to the browser’s back button, which rewind to the previous page
  • forward()
    • The browser’s equivalent of a forward button that advances to the next page
  • go(number)
    • comprehensivebackandforwardMethod, which takes an integer as an argument, with a positive number representing forward, a negative number representing backward, and a value representing the number of pages to jump

Screen

Represents information about the user’s screen, through which information about the user’s display can be obtained

Except for the window itself, which is a global variable, all BOM objects are stored as properties of the window and can be used either through the window or directly

The timer

Start timer

The setInterval() method and the timer method are both window object methods and can be written directly.

var timer = setInterval(Callback function, execution interval,[callback function argument....] );Copy the code

The execution interval is a positive integer, indicating milliseconds.

The return value is a Number, which is used as the unique identifier of the timer and is used to turn off the timer.

Off timer

The clearInterval() method is used to turn off the timer

CleartInterval (timer identifier);Copy the code

The timer id is the value returned when the timer is enabled.

Any argument can be accepted, and if the argument is a valid timer id, the corresponding timer is turned off.

If the argument is an invalid arbitrary argument, no error is reported and no response is generated.

Turn on retarder

The setTimeout() method enables delayed calls

setTimeout(Callback function, delay time,[callback function parameter....] )Copy the code

The delay time is a positive integer, indicating milliseconds.

The return value is a data of type Number, which is used as a unique identifier for the delayer.

JSON

Objects in JS are only known by JS, not by any other language.

JSON is a special format string, which can be recognized by any language, and can be converted into objects in any language. JSON is mainly used for data interaction in development.

JavaScript Object Notation JS Object Notation.

The format of the JSON object is the same as that of the JS object, except that the attribute names in the JSON string must be quoted.

JSON classification

  1. object{}
  2. An array of[]

The value allowed in JSON

  1. string
  2. The numerical
  3. Boolean value
  4. null
  5. Objects (other than functions)
  6. An array of

JSON – > JS object

In JS, we have a utility class called JSON.

This object will help you convert a JSON object into a JS object and vice versa.

var json='{"name":" sun Wukong ","age":18,"gender":" male "}';
var o=JSON.parse(json);
console.log(o);
Copy the code

Parse () is used whenever a JSON string is converted to a JS object.

JS object – > JSON

var o={"name":"Sun Wukong"."age":18."gender":"Male"};
var json=JSON.stringify(o);
console.log(typeof json);
Copy the code

Use the stringify() method whenever you convert a JS object to a JSON string

compatibility

JSON is not supported in IE7.

In IE7 you can use the eval() function.

This function can be used to execute a string of JS code and return the result of the execution.

If a string executed using eval() contains {}, it treats {} as a code block and does not want to parse it as a code block, wrapping the string in parentheses.

Matters needing attention

In development, the eval() function is not recommended.

This function is inefficient and has security risks.

If you need JSON operations compatible with IE7 and below, you can do this by importing an external JS file (json2.js).

cookie

// Cookie session tracking client (front-end)
//session Session tracing technology server (back-end)

// Cookie: Saves data from the web page to the browser
Note: Cookies do not save any data by default
// The cookie type is a string. The string is in the key-value pair format. Multiple data cannot be saved at a time
// Save multiple data needs to be set one by one
// The number limit is 20-50. The size limit is around 4KB depending on the browser
document.cookie="key=value;";
// Cookie life cycle: Clears by default at the end of a session (close browser).
// Set cookie expiration time expires=
var date=new Date(a); date.setDate(date.getDate()+1);// Set it to tomorrow
document.cookie="key=value; expires="+date.toGTMString()+";";
// After the expiration time is set, the cookie retention time is only affected by time, not by browser shutdown
// Cookies can only be accessed from pages in the same browser and folder
// Cookies can be accessed by all server pages
document.cookie="key=value; path=/;";
// For example, a cookie is saved in www.it666.com,
// Then we cannot access the cookie in edu.it666.com
document.cookie="key=value; domain=it666.com;";
Copy the code

Cookie method encapsulation

function addCookie(key,value,day,path,domain){
//1. Handle the default save path
    var index=window.location.pathname.lastIndexOf('/');
    var currentPath=window.location.pathname.slice(0,index);
    path=path||currentPath;
//2. Process the domain saved by default
    domain=domain||document.domain;
//3. Handle the default expiration time
    if(! day){document.cookie=key+"="+value+"; path="+path+"; domain="+domain+";";
    }else{
        var date = new Date(a); date.setDate(date.getDate()+day);document.cookie="";
        document.cookie=key+"="+value+"; expires="+date.toGMTString()+"; path="+path+"; domain="+domain+";"; }}function getCookie(key){
    var res=document.cookie.split(";");
    for(var i = 0; i <res.length; i++){var temp=res[i].split("=");
        if(temp[0].trim()==key){
            return temp[1]; }}}// Only cookies in the default path can be deleted
function delCookie(key,path){
    console.log(key,getCookie(key));
    addCookie(key,getCookie(key),-1,path);
}
    delCookie("asd");
};
Copy the code

WebStorage

HTML5 provides two new ways to store data on the client side: localStorage and sessionStorage, mounted under the Window object.

WebStorage is local storage and data is not transferred by request from the server. Thus it can store large amounts of data without affecting the performance of the site.

The purpose of Web Storage is to overcome some of the limitations imposed by cookies. When data needs to be tightly controlled on the client, it does not need to continuously send data back to the server. For example, the client needs to save some user behavior or data, or get some data from the interface will not be updated in the short term, we can use Web Storage to store.

localStorage

The life cycle of localStorage is permanent. Data stored in localStorage, even if the browser is closed, will not let the data disappear, unless the initiative to delete data. If you want to set the failure time, you need to package yourself.

sessionStorage

The life cycle of sessionStorage is before the browser closes.

Features:

  • Closed browser sessionStorage failure;
  • Page refreshes do not erase data;
  • Use window.open to open the page or change localtion. Href mode to get the data inside the sessionStorage.
storage Action and characteristics Storage quantity and size api
cookie Store user information and connect to the server to obtain data.

The data that can be stored is limited and depends on the server. Therefore, do not store the data of the server in cookies to avoid affecting page performance.

You can set the expiration time.
It is best to keep the cookie within 4095B, and any additional data will be ignored.

IE6 or later store up to 20 cookies; IE7 and later versions can have a maximum of 50; Firefox up to 50; Chrome and Safari don’t have hard limits.
Native, $. Cookies
localStorage Store client information without requesting the server.

Data is stored permanently unless the user manually cleans the client cache.

The developer can encapsulate a method and set the expiration time.
The storage space varies with browsers. (Those who are interested can try it out for themselves). localStorage.setItem(‘key’, ‘value’);

let data = localStorage.getItem(‘key’);

localStorage.removeItem(‘key’);

localStorage.clear();
sessionStorage Store client information without requesting the server.

The data is saved in the current session. The data is not cleared when the page is refreshed, and the data on the end session (closing the browser, closing the page, or jumping to the page) becomes invalid.
With localStorage With localStorage

supplement

True/false array conversion (compatible)

// True array --> pseudo array
var zhen=[1.2.3];/ / array
var wei={};/ / false array
[].push.apply(wei,zhen);
// False array --> true array
var zhen=[];/ / array
var wei={'0':'wc'.'1':'20'.length:2};/ / false array
[].slice.call(zhen,wei);
Copy the code

Garbage collection mechanism

Abbreviations: GC

Unreachable objects are garbage

The garbage will be picked up automatically