Many javaScript methods have very flexible parameters and the number of parameters they take. Think about what this means!

Es6 ++(Next) section please go to juejin.cn/post/698665…

1. Basic grammar

  • 1.1 introduced
/ / inline try < a href = "javascript: void (0)" onclick = "alert (' ok ')" > click < / a > / / embedded < script > alert (" ok "); </script> </script> </script>Copy the code
  • 1.2 Debugging Output
Alert (*): Pops content through a dialog box to the browser confirm(message) method to display a dialog box with a specified message and a confirm and cancel button. This method returns true if the visitor clicks OK, false otherwise. Document.write (*): outputs the content directly to the browser console.log(*): outputs the content to the browser console console.log('hello'); The console. The info (' information '); The console. The error (' error '); Console. table(arr or obj): Output the array and obj object contents to the browser console console.dir(obj) displays all the properties and methods of an object. Console.trace () is used to trace function calls. Console.time () and console.timeend (), which display the running time of the code. Console.profile () performance analysis console.assert(a==b) is used to determine whether an expression or variable is true. If the result is no, a message is printed to the console and an exception console.dirxml(node) is thrown to display the HTML/XML code contained in a node (node) of the page. Console. log("%d year %d month %d day ",2011,3,26); console.log("%d year %d month %d day ",2011,3,26);Copy the code
  • 1.3 the statement
Javascript is case sensitive javascript ignores extra whitespace javascript is a scripting language, and the browser executes the script line by line as it reads the code. For traditional programming, all code is compiled before execution (interpreted languages). Programs count from 0 to the end of javascript codeCopy the code
  • 1.4 annotations
Single-line comment: (double slash) // comment Multi-line comment: /* Gaze */Copy the code
  • 1.5 variables:
The container variables are named according to the following rules: the variable name consists of letters, digits, underscores (_), and $, and cannot start with a number: var username = 'zhangsan'; Var username = 'zhangsan', age = 30, sex = 'zhangsan'; Declare variables but do not assign values: var username; // Don't use var to declare variable username = 'zhangsan'; It is a good programming practice to uniformly declare the required variables at the beginning of the code.Copy the code
  • 1.6 Data Types
String (String), Number (Number), Boolean (Array), Object (Object), Null (Undefined) detect data types using Typeof Object. The prototype. ToString. Call (obj). Slice (8-1) / / string describing an Object data types, such as custom objects are not covered, will return to "[Object type]"Copy the code
  • 1.6.1 String (String)
• Use single and double quotation marks to define strings • What needs to be noted about single and double quotation marks • Single and double quotation marks are the same and do not parse variables • Single and double quotation marks can be nested within each other • They cannot be nested within themselves unless escaped using escape charactersCopy the code
  • 1.6.2 Numbers
• NaN(Not a number) • NaN is equal to any value, including itself • isNaN(): determines if a value isNaNCopy the code
  • 1.6.3 Boolean (Boolean)
true
false
Copy the code
  • 1.6.4 array
Var cars = new Array(); cars[0] = 'BMW'; cars[1] = 'BYD'; cars[2] = 'BenZ'; Var cars = new Array('BMW', 'BYD', 'Benz'); Var cars = ['BMW', 'BYD', 'Benz']; Var shoplist = ['zhangsan',20,true,null,undefined,[1,2,3],{}]; // 5. A common compound data (waterfall flow, $scope.shoplist) var shoplist = [{id:1,username:"zhangsan",age:20,sex:" male "}, {id: 2, the username: "lisi", the age: 18, sex: "female"}, {3, id: username: "wangwu, age: 32, sex:" male "};Copy the code

1.6.5 object

1. {} var obj = {username:"zhangsan", age:20, sex:" male ", say:function(){}, eat:function(){}} 2. Var obj = new Object(); obj['username'] = 'zhangsan'; obj.age = 20; Function Ball(){this.x = 100; obj.say = function(){} this.y = 100; this.radius = 50; This.draw = function(){}} var b = new Ball(); Let obj={["key"]:12} let keys="key" let obj={[keys]:12} let obj={} obj["key"]=12 let keys="qwe" let obj={} obj[keys]=12 console.log(obj[keys],obj.key,obj["key"])Copy the code
  • 1.6.6 Undefined
• Undefined variable alert(typeof age) • undefined variable var sex; alert(typeof age)Copy the code
  • 1.6.7 Null
• Empty references • Set the value to NULL to empty variables Note the difference between object.create (null) and {}Copy the code
  • 1.6.8 = = = = =
The difference between == and === : Whether to cast == Comparison principle: For ==, if the two sides of the comparison are of different types, a cast is performed. The process is as follows: First, it determines whether the two types are the same. If it's the same size, if it's not the same type, then it does a cast and it checks if it's comparing null and undefined, if it is, it returns true and checks if it's string and number, If it's true, it converts the string to a number to determine whether one of the strings is Boolean, if it's true, it converts the Boolean to a number and then evaluates whether one of the strings is object and the other is string, number, or symbol, ToString () === = if the type of the object is the same as that of the toString(), return false; Otherwise, continue comparing the two valuesCopy the code
  • 1.7 Mutual conversion of data types
  • 1.7.1 Converting to a String
String()
Copy the code
  • 1.7.2 Converting to A Boolean
• Boolean() • "0 0.0 NaN false null undefined->false • all others are true (' false ', '0', 'null')Copy the code
  • 1.7.3 Conversion to values does not include conversion between bases
• Number() ordinary string ->NaN pure Number string, numeric -> prototype output empty string ", blank string ",null->0 true->1 false->0 undefined->NaN • parseInt() • parseFloat() searches from the first character until it finds an illegal character (other than the number and the first decimal point) and returns the number foundCopy the code
  • 1.8 the operator
  • 1.8.1 Arithmetic operators
    +  -  *  /  %  ++  --
Copy the code
  • 1.8.2 Assignment operators
   =  +=  -=  *=  /=  %=
Copy the code
  • 1.8.3 Connection operator +
• + is pure numbers on both sides: + stands for addition • Otherwise, + is concatenationCopy the code
  • 1.8.4 Comparison operators
= = = = =! =! = = > < <= > >=Copy the code
  • 1.8.5 Logical Operators
&& () two really is true, the rest are all false, | | (two false is false, the rest is true),! (the)Copy the code
  • 1.8.6 Conditional Operators (ternary Operators)
3 = = 3? value1 : value2; // value1Copy the code
  • 1.8.6 Expression evaluation operators
let data={} data.obj? .objCopy the code
  • 1.9 Flow control: conditional statements
  • 1.9.1 If Conditional Statement (Range Determination)
let arr=[]
if (Array.isArray(arr.children)&& arr.children.length){
  // option
}
Copy the code
  • 1.9.2 Switch Statement (Specific Value Determination)
var month = 1; Switch (month) {case 1: case 3: case 5: case 7: case 8: case 10: case 12: console.log('31 days '); switch (month) {case 1: case 3: case 5: case 7: case 8: case 10: case 12: console.log('31 days '); break; Case 4: case 6: case 9: case 11: console.log('30 days '); break; Case 2: console.log('28 days '); break; Default: console.log(' There was a problem with the entered month '); }Copy the code
  • 2.0 Flow control – loop statements
  • 2.0.1 for loop
for (var i = 0; i<=10; i++){ ((i)=>{ setTimeout(()=>{ console.log(i) },i*1000) })(i) }Copy the code
  • 2.0.2 while loop
  var i = 0; while (i>0){}
Copy the code
  • The 2.0.3 do… The while loop
var i = 0; do { console.log(i); i++; } while (i=100)
Copy the code
  • 2.0.4 for… The in… (Key or index) loop
Var data = {username: username,age:20,sex:' male '}; for (var i in data) { console.log(i+'===>'+data[i]); }Copy the code
  • At 2.0.5 for… Of… (value) loop
Var data = {username: username,age:20,sex:' male '}; for (var i of data) { console.log(i); }Copy the code
  • 2.0.6 Break and continue statements
Break is the end of the loop and continue is the end of a loop for (var I = 0; I < 10; i++){ if( i % 2 === 0){ continue } cnsole.log(i) }Copy the code
  • 2.0.7 Universal cycle
Custom implementation by callback inside return a whole cycle can be terminated by the false like forEach off use iterators, and can traverse object, array type judgment, such as loop termination methods, iterator design patterns, the callback function, Function each(object, Var type = (function (obj) {switch (obj.constructor) {case Object: return 'Object'; break; case Array: return 'Array'; break; case NodeList: return 'NodeList'; break; default: return 'null'; break; } })(object); // If it is an array or a class array, return: Index, value the if (type = = = 'Array' | | type = = = 'NodeList') {/ / because of class Array NodeList, so can't directly call every method []. Every call (object, function (v, i) { return callback.call(v, i, v) === false ? false : true; }); Else if (type === 'Object') {for (var I in Object) {if (callback.call(Object [I], I, object[i]) === false) { break; }}}}Copy the code
  • 2.1 Regular Expressions
  • 2.1.1 metacharacters
[0-9] : an arbitrary number. [a-z] : any lowercase letter (x | y) : matching x or y (to match one of these), [^ 0-9] : matching an arbitrary non-numeric. [\ d] : an arbitrary number. [\ s] : any blank character (\ r \ n \ t) [\ W]: approximately equal to a-za-z0-9_ • ^[a-z]{6,12}$: must be 6-12 lowercase lettersCopy the code
  • 2.1.2 quantifiers
• is equal to {0,} any number • is equal to {1,} at least one •? Equivalent to {0,1} at most • {6,18}Copy the code
  • 2.1.3 Mode modifier
• I: case insensitive • g: performs global matching • m: performs multi-line matchingCopy the code
  • 2.1.3 Mode modifier
• str.match(reg) // Reg matches the string STR, Replace (/\B([a-z])/g, return null or [] • reg.test(STR)/ / if STR satisfies the regular • str.replace(/\B([a-z])/g, '- $1). ToLowerCase () / / small hump STR into a hyphen, STR., replace (/) (\ w * - *) (\ w/g, function ($1, $2, $3) {return $2 + $3 [0]. ToUpperCase () + $3. Slice (1)}) / / hyphen into small humpCopy the code
  • 2.2 JSON: Objects with attributes only
  • 2.2.1 JSON function
Json.input error is raised when the first character is parsed and written in memoryCopy the code
  • 2.2.2 instance
{"username":"zhangsan", "age":20, "sex":" male "}Copy the code

2.2.3 JSON method

Parse () • Convert Javascript objects to JSON strings: json.stringify ()Copy the code
  • 2.3 the function
  • 2.3.1 Function Definition
Function demo(){console.log(' the first way to define a function '); } • Anonymous function(function(){console.log(' second way to define functions '); New Function('x','y','return x+y; ');Copy the code

2.3.2 Features of functions

• Common functions within the same script tag can be called first and then defined, but cross-script tags are not supported • functions defined without calling are not written • functions with the same name are overwritten without error • scope of variables • Variables declared outside the function are global variables, • Variables declared by var in a function are local variables and can only be called in a function • Variables defined as global variables in a function • Number of arguments • parameters > arguments: The value of any extra parameter is undefined • arguments > parameters: Superfluous arguments are ignored • argument the built-in object of the function • An object consisting of all arguments built into the functionCopy the code
  • 2.3.3 Classification of functions
$.get('1.php',function(MSG){$.get('1.php'); If (MSG == 'yes') {spanobj. innerHTML = 'the user name is available '; } else {spanobj. innerHTML = 'The user name is already registered '; 1.AngularJS getShopIndex(ID) and getCartIndex(ID) are both functions that return the corresponding index 4. Function demo(){return 'ok'; } var d = demo(); alert(d); function test(){ alert('ok'); } var t = test(); alert(t);Copy the code
  • 2.4 Built-in Objects
  • 2.4.1 Array Array objects
Arr. Length: array arR length • arr. Join (*): Joins all elements in the array into a string with *. • Arr.push (*): Adds one or more elements to the end of the array and returns the new length. • Arr.pop (): Used to delete and return the last element of the array. • Arr.shift (): Removes the first element from an array and returns the value of the first element. • Arr.unshift (): Adds one or more elements to the beginning of an array and returns a new length. • arr.sort([function: sort]):arr.sort(function(a,b){return a-b; }) to sort the elements of an array. • Arr.reverse (): Used to reverse the order of elements in an array. All of the above changes the original array; • Arr.indexof (*): Returns the position at which a specified string value first appears in a string. • Arr.lastIndexof (*): Returns the last position of a specified string value, searched from back to front at a specified position in a string. • Arr. slice(start position, end position): Retrieves a specified fragment in the array (not including the end position): extracts a portion of the string and returns the extracted portion in a new string. • Arr.splice (starting position, length): Adds or removes elements from an array. • arr. Map (function(currentValue,index,arr){// return newValue about currentValue or other option}, ThisValue): handles each element of the array by specifying a function and returns the processed array. • Arr. Filter (function(currentValue,index,arr){return newValue about currentValue or other option}, ThisValue): checks for filtered numeric elements and returns an array of all elements that match the condition. • Arr. Some (function(currentValue,index,arr){return bool}, thisValue): Until a value is found that causes callback to return a "true" value (which can be converted to a Boolean true), some will immediately return true if such a value is found. Otherwise, some returns false. • arr. Every (function(currentValue,index,arr){return bool}, thisValue): • arr. Reduce () : [x1, x2, x3, x4]. Reduce (function f(x,y){return newvalue about xANDy})) = f(f(f(x1, x2), x3), x4), Array reduce() applies a function to Array [x1, x2, x3...]. The function must take two arguments, reduce(), and proceed to the next element of the sequence for a cumulative calculation.Copy the code

• New Boolean(value); // The constructor returns true or false and a Boolean object. Boolean (value); Description: When called as a constructor (with operator new), Boolean() converts its argument to a Boolean value and returns a Boolean object containing the value. When called as a function (without the operator new), Boolean() simply converts its argument to a raw Boolean value and returns that value. Note: This object is set to false if the value argument is omitted, or if it is 0, -0, null, “”, false, undefined, or NaN. Otherwise set to true (even if the value argument is the string “false”).

  • 2.4.3 the Date object
• var d = new Date() • new Date() new Date() new Date() new Date('2019/1/10 0:28:30') • d.goetfullYear (): year • D.goetmonth (): month • D.goetdate (): day • D.goethours (): hour • D.goetminutes (): second • d.goetseconds (): milliseconds • D. goetTime (): timestamp extension date.prototype. format:  Date.prototype.format = function(format) { //new Date( year, month, date, hrs, min, SEC) //new Date() // The argument can be an integer or a string, but the format must be correct. New Date(2009,1,1) // correct new Date("2009/1/1") // correct //example new Date(). Format (" current Date: yyyy-mm-dd, week W, yyyy-mm-dd, time: hh:mm:ss:c") let o = { "Y+": this.getFullYear() + '', "M+": this.getMonth() + 1, //month MM "D+": this.getDate(), //day DD "h+": this.getHours(), //hour hh "m+": this.getMinutes(), //minute mm "s+": This.getseconds (), //second ss "Q+": Math. Floor ((this.getMonth() + 3) / 3), //quarter Q "c+": This.getmilliseconds (), //millisecond c "W": [' one ', 'two ',' three ', 'four ',' five ', 'six ', [this.getDay() -1] //week week} for (let k in o) {if (new RegExp("(" + k + ")).test(format)) {format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr((("" + o[k]).length >= 2 ? 2 : ("" + o[k]).length))) } } return format }Copy the code
  • 2.4.4 Math object
• PI: the ratio of the circumference of a circle to its diameter. This value is approximately 3.141592653589793 method • abs(): absolute value of the returned number • ceil(): performs the rounded up calculation, which returns an integer greater than or equal to the function argument, and the nearest integer • floor(): performs the rounded down calculation, It returns less than or equal to the function argument, And the nearest integer • round(): rounds a number to the nearest integer • Max (): the number of two specified numbers with the larger value • min(): the number of two specified numbers with the smaller value • Random (): a random number between 0 and 1 • Sine (*), cosine (*),tan(*): trigonometric function, * is in radians, 1 degree in radians written as 1* math.pi /180. • Asin (x), acos(x) inverse trigg function, x is a number between -1.0 and 1.0, returns the radian value between 0 and PI, otherwise returns NAN. • Atan (x) denotes the inverse tangent of x, which returns a number between -pi/2 and + PI /2. • Atan2 (y, x) evaluates the inverse tangent of y/x and returns a number between [-pi,+ PI].Copy the code
  • 2.4.5 Number object
• MAX_VALUE: the maximum Number • MIN_VALUE: the minimum Number • toFixed(): the Number is rounded to the specified decimal Number • Number("123456.123456").tolocaleString () // "123456123" this method is the default decimal places most keep only 3 Number. The prototype. ToLocaleString (locales, options) locales: 'useful - Hans - CN' options: { MinimumIntegerDigits: The minimum number of integer digits to use. Possible values range from 1 to 21, with the default being 1. MinimumFractionDigits: The minimum number of decimal places to use. Possible values range from 0 to 20; By default, the normal number and percentage format is 0. The default currency format is provided by the ISO 4217 Currency code list (value 2 if not provided in the list). MaximumFractionDigits: The maximum number of decimal digits to use. Possible values range from 0 to 20; The default value for the pure numeric format is minimumFractiondigits and the one larger than 3; The default currency format is minimumfractiondigits and ISO 4217 currency code list which is larger (2 if not provided in the list); The percentage format defaults are minimumFractiondigits and the one larger than 0. MinimumSignificantDigits: use the minimum number of significant digits. Possible values range from 1 to 21; The default value is 1. MaximumSignificantDigits: use: the maximum number of significant digits. Possible values range from 1 to 21; The default is 21. Notation: Format for the number to be displayed. Default is "Standard". Standard "Digital only format;" Scientific "Returns the size order of formatted numbers;" Engineering "returns an index of ten when divided by three;" Compact "represents an index string, using the" short "format a by default; CompactDisplay "only used when notation is" compact ", using "short" (default) or "long"}Copy the code
  • 2.4.6 String object
• length: length • split(): Splits a string into an array of strings for example split(" ") returns an array of words; • Match (): Retrieves a specified value within a string, or finds a match for one or more regular expressions • Replace (): Used to replace some characters with others in a string, • Slice (start,end): extracts a portion of the string, • indexOf(): The first occurrence of a specified string value in a string • lastIndexOf(): The last occurrence of a specified string value, • charAt(): Returns the character at the specified position • charCodeAt(): The Unicode encoding corresponding to the letter at the specified position • String.formcharCode (): Converts the Unicode encoding to a characterCopy the code

2.4.7 RegExp object

• reg.test(STR): Uses regular expressions to test whether STR meets the requirementsCopy the code
  • 2.5 Change the use of apply(),call(), and bind() for this pointer
• JavaScript has a completely different mechanism for handling this than other languages. There are five different cases where this refers to something different. • a global scope this; It's going to point to the global object. The JavaScript script running in the browser. The global object is window. • the b function calls func*(), where this also points to the global object. ES5 Note: In strict mode, there are no global variables. In this case this will be undefined. • The c method calls some.func* (), and this refers to some objects. • d calls the constructor new func* (); A function is called a constructor if it tends to be used with the new keyword. Inside the function, this points to the newly created object. • Apply, call, and bind are all used to change the direction of the function's this object; • The first argument to apply, call, and bind is the object to which this refers, i.e. the context that you want to specify; • Apply, call, and bind can all be passed with subsequent parameters; • Bind returns the corresponding function for later call; Apply and call are immediate calls. var obj = { x: 81, }; var foo = { getX: function() { return this.x; } } console.log(foo.getX.bind(obj)()); //81 console.log(foo.getX.call(obj)); //81 console.log(foo.getX.apply(obj)); • Use bind(), followed by parentheses, when you want a callback instead of an immediate context change. Apply/Call executes the function immediately. • apply() somefunc.call(this scope refers to the target object, [arg1,... argn]) • Call () somefunc.call(this scope refers to the target object, arg1... Argn) • bind () somefunc. Call (arg1, argn) • bind () somefunc. Call (arg1, argn) • bind () somefunc. ,argn)Copy the code

2.BOM (Window object)

  • 2.1 Global properties and functions
• All global variables are properties of the Window object • All global functions are methods of the window object • System methods • Alert () • Confirm () is used to display a dialog box with a specified message and OK and cancel buttons • Prompt () prompts the user for input • moveTo() moves the upper left corner of the window to a specified coordinate. • resizeBy() resizeTo() resizeTo() resizeTo the window to the specified width and height • scrollBy() scrolls the content to the specified pixel value, • scrollTo() scrolls the content to the specified coordinate • open(' 1.html ', ", 'width=200,height= "200"): opens a new window • Close (): closes the window • • setInterval() calls a function or evaluates an expression at the specified interval (in milliseconds), • setTimeout() calls a function or evaluates an expression after the specified number of milliseconds, • clearInterval(timeout) unsets setInterval() • clearTimeout(timeout): Cancels the timeout set by the setTimeout() methodCopy the code
  • 2.2 Navigator Objects (browser-related information)
• appCodeName returns the code name of the browser. • appName Returns the name of the browser. • appVersion Returns the platform and version information of the browser. • cookieEnabled Returns a Boolean value indicating whether cookies are enabled in the browser. • Platform Returns the operating system platform running the browser. • userAgent returns the value of the user-Agent header of the server sent by the client. • userLanguage returns the OS's natural language Settings.Copy the code
  • 2.3 Screen objects (screen-related information)
• Width • height • availHeight: Returns the height of the display screen (except for the Windows taskbar). • availWidth: Returns the width of the display screen (except for the Windows taskbar).Copy the code
  • 2.4 Frames object: Returns all the named Frames in the window
  • 2.5 History object (History of the current browser)
• length: returns the number of urls in the browser history list • back(): loads the previous URL in the history list. • Forward (): loads the next URL in the history list. • Go (): loads a specific page in the history list • history.pushState(data, ", subscript) is used in conjunction with window.onpopState ()Copy the code
  • 2.6 Location Object (URL of the current browser)
• hash: anchor history rollback • window.onhashchange() • href • reload()Copy the code

The HTML DOM object

  • 3.1 DOM Document Objects
  • 3.1.1 Form object
• Document. forms[0] • document.forms['formName'] • document.formName • Form element object: formobj.inputNameCopy the code
  • 3.1.2 the Select objects
Property: Disabled Length selectedIndex Method: add() remove()Copy the code
  • 3.1.2 Table Table object
• table.deleterow (index) : • Row.cells: Gets the cell object • row.insertCell(index) : adds the cellCopy the code
  • 3.1.3 Cookie object
document.cookie = 'username=zhangsan; expires=date; path=/; domain=qq.com; secure' cookie.get()/set()Copy the code
  • 3.1.4 localStorage and sessionStorage
2. LocalStorage will be able to directly store the data requested for the first time to the local, which is equivalent to a database with a size of 5M for the front-end page, which can save bandwidth compared to cookie. However, this is a limitation of localStorage that is supported only in older browsers. The localStorage property is supported only in IE8 and later versions of IE. 3, localStorage in the browser privacy mode is unreadable 4, localStorage is essentially a string read, if the storage content will consume memory space. The only difference between localStorage and sessionStorage is that localStorage belongs to permanent storage, while sessionStorage belongs to when the session ends. Key/value pairs in sessionStorage will be cleared. Parse (localStorage[" somekey "]); localStorage[" somekey "]= json.stringify (value); / / take localStorage. The getItem (" somekey "); SetItem (" somekey ",value); Localstorage.removeitem (" somekey ",); // Delete a cache localstorage.clear (); Var storage= window.localstorage; storage.a=1; storage.setItem("c",3); for(var i=0; i<storage.length; i++){ var key=storage.key(i); console.log(key); } sessionStorage is similar to localStorageCopy the code
  • 3.2 DOM functions (Determine what the DOM does by functions)
  • 3.2.1 Obtain and Change HTML tags
Document. GetElementById (), the document. The getElementsByTagName (), the document. The getElementsByName () Document. QuerySelector (' CSS selector # box. A div) : match the first element of the composite conditions, the document. The querySelectorAll () : Element matching all compound conditions • ID name obtained directly (for testing purposes, not recommended for formal environments)Copy the code
  • 3.2.2 Get and change HTML attributes
• obj.src • obj.getAttribute('attr'): Gets the value of the attribute by name • obj.setAttribute('attr','value'): creates or changes a new attribute • Obj.removeattribute ('attr'): Removes the specified attributeCopy the code
  • 3.2.3 Obtaining and changing CSS styles
Function getStyle(obj, attr){return obj.currentStyle? obj.currentStyle[attr] : document.defaultView.getComputedStyle(obj, null)[attr]; }Copy the code
  • 3.2.4 Event Handling
  • 3.2.4.1 Mouse Events

• onClick: single machine • ondblClick: double click • onContextMenu: right click • onMouseover: Move in • onMouseout: remove out • onMouseDown: press down • onMouseup: lift up • Onmousemove: mobile

  • 3.2.4.2 Keyboard Events
• onkeyDown: pressed • onkeyUp: lifted • onkeyPress: occurs when a keyboard key is pressed and a key is releasedCopy the code
  • 3.2.4.3 Form Events
• onfocus: focus • onblur: out of focus • onsubmit: submit • onchange: form element change event • onReset: reset button when clicked • onSelect: text selectedCopy the code
  • 3.2.4.4 Framework Object Events
• OnLoad: when the page is loaded • onunload: the user exits the page • onresize: when the page size changes • onError: when the image load fails • onabort: the image load is interrupted • Onscroll: when the page is being rolled • Lazy loading: onscrollCopy the code
  • 3.2.4.5 Mouse and Keyboard Attributes
• altKey:Alt is pressed and held • shiftKey: • ctrlKey: • clientX: mouse pointer to the horizontal coordinate of the browser page (or client area) • clientY: Mouse pointer to the vertical coordinate of the browser page (or client area)Copy the code
  • 3.2.4.6 An Event Bubbles
• Event.stopPropagation () prevents the event from bubbling. the following code continues • event.cancelBubble = true Notice return false; Represents the termination function, after which the code will not be executedCopy the code
  • 3.2.4.7 A Default TAB event Behavior (preventDefault)
• Click a link to jump to the page by default • Click the submit button to submit the form by default • Click the right mouse button to appear the right menu • A tag to create anchor point click a to automatically scroll to Baidu content div <a href="# bidu-id "> Baidu </a> <div <a href="javascript:void(0);" "> </a> </ b form formobj.onsubmit = function(){return false; }Copy the code
  • 3.2.4.8 Js Default Event binding and unbinding
var btn = document.getElementById("btn"); Function (){alert("btn1 event bound successfully!" ); } unbind: btn1.onclick =null; Alert (" Btn1 bound event has been removed! ); } second type of attachEvent binding: btn.attachevent ('onclick',function(){alert('1'); }); Btn.detachevent ('onclick',function(){alert('1'); }); Btn.addeventlistener ('click', function(){alert('1'); },false); Btn.removeeventlistener ('click', function(){alert('1'); },false); Note: Multiple registrations of the same event will cause event accumulation and bubbling. Please cancel the event before registration and register again.Copy the code
  • 3.2.4.9 Real-time monitoring of value changes of node(selected DOM) nodes (SELECT, Input, textarea)
  var node = document.getElementById("inputele");
  node.addEventListener('input', function(e) { 
     console.log(e.target.value);
  })
Copy the code
  • 3.3 DOM Node Operations
  • 3.2.1 Attributes of the label Element
• Attributes: attributes return the NamedNodeMap containing the selected node attributes • className: attributes can be set or return the element's class attribute • childNodes/ Children: collection of all children /children • The first child node/firstChild/firstElementChild: the first element child nodes, lastChild/lastElementChild: the last child node, / the last element child node NextSibling/nextElementSibling: the next node/previousSibling/previousElementSibling: the next element node/a brother node before, an element node ParentNode: locates a node and finds its parentNode. • nodeName: specifies the nodeName. • nodeType: specifies the nodeType. • nodeValue: specifies the nodeValue. • innerHTML: Gets or sets the contents of the element, • clientHeight: Gets the height of the browser • offsetHeight: Gets the height of the div object (width = width + border thickness +padding) • • offsetLeft: Gets the left distance of the div from the page (if the parent element has a position, relative to the parent element) • offsetTop: Gets the distance from the page (if the parent element has a position, relative to the parent element) • scrollHeight: gets the total height of the page • scrollTop: gets the height of the browser scroll • scrollLeft: gets the width of the browser scrollCopy the code
  • 3.2.2 Method of labeling elements
• appendChild(): adds a new child to the end of a node's list of children • insertBefore(): inserts a new child before an existing child • replaceChild(): replaces a child with another node • • cloneNode(): creates an exact copy of the specified nodeCopy the code

Brower object

  • 4.1 the window object
var window = window || {}; window.addComment = function () { }; window.adsbygoogle = function () { }; window.alert = function () { }; Window.applicationcache = function () {}; window.applicationCache = function () {}; // Convert the ASCII string or binary data to a base64 encoded string decode window.atob(); // Encode window.btoa("Hello, world"); / / share window. BdShare (); // Move the keyboard focus away from the top window. window.blur(); // It is used to store Response objects. In other words, it's used to cache HTTP responses. Although localStorage can also do this, it is probably more professional. window.caches(); Window. / / cancel a previously by calling requestAnimationFrame animation frames of () method to add to the plan request. Window. CancelAnimationFrame (); // requestIdleCallback is a new API. When the browser takes a breather, Used to perform less important background planning task window) requestIdleCallback () / / registration window to capture all events window of the specified type. The captureEvents (); // Cancel timeout set by setInterval(). The parameter must be the ID returned by setInterval(). Window.clearinterval (); / / same as above the window. The clearTimeout (); // Contains information about the Web browser window.clientInformation() // Closes the current page window.close(); Window.confirm (); // Bitmap clipping returns a bitmap that can be set to width and height attached :demo window.createImageBitmap(); var canvas = document.getElementById('myCanvas'), ctx = canvas.getContext('2d'), image = new Image(); image.onload = function () { Promise.all([ createImageBitmap(this, 0, 0, 32, 32), createImageBitmap(this, 32, 0, 32, 32) ]).then(function (sprites) { ctx.drawImage(sprites[0], 0, 0); ctx.drawImage(sprites[1], 32, 32); }); } image.src = 'https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=1349487841, & FM = 85 & 1262002022 s = E1B876DBCA1075C4922022380300D057'; // data encryption window.crypto(); // The document object window.document // Fetch API provides an interface to Fetch resources (including cross-domain). Anyone who has ever worked with XMLHttpRequest should be able to get started, but the new API offers a much more powerful and flexible set of features. Window.fetch () // Search string returns true or false window.find(); / / print window. The print (); // Allow Web pages to access certain functions to measure the performance of Web pages and Web applications, Including Navigation Timing apis and high resolution time data window. The Performance () = = > now | | mark / / screen window. The screen ();Copy the code