JavaScript is an object-oriented, dynamic language, and its syntax is derived from Java and C, so many of the syntactic features of both languages are equally applicable Used in JavaScript. One major difference to note is that JavaScript does not support classes, the concept of classes in JavaScript through object prototypes Object Prototype (see Classes here for ES6 Classes). The other major difference is in JavaScript Functions are also objects, and JavaScript allows functions to be passed like any other object while containing executable code. 1. The script tag can be placed in head or body because browsers interpret HTML files sequentially, and records are used to initialize the page The JS of CSS code should be placed in the head, and there is no requirement for the location of function functions that are executed by time calls The js code is best placed at the bottom of the page, referring to the external script file format: <script SRC =”script.js”></script> Type =text/javascript 3, the document. The write (” “); Write content directly in the web page, // to write double quotation marks, output is the content of double quotation marks Three ways:
The first: output content with “” enclosed, direct output “” number of content Second: output content through variables Third: output a number of content, content with a + link. Fourth: output HTML tags, and the effect, the tags use “” parentheses.
4, document.getElementById(“id name “); Manipulate HTML elements with the specified ID attribute
/**/ 6. Define variable rules: Variable names can be arbitrary, but follow the naming rules:
1. Variables must start with a letter, underscore (_), or dollar character ($).
2. Use any number of letters, digits, underscores (_), or dollar signs ($).
3. Do not use JavaScript keywords and JavaScript reserved words Variables are declared before they are assigned: var mychar=”hello”; Variable repeatable assignment: var mychar; mychar=”javascript”; mychar=”hello”; 7. Form forms are sometimes used to jump after submitting events, or a window or a page is wrapped with form forms <form action=”” method=”get/post”></form 8, Alert message dialog box: there is a confirm button Alert (string or variable); <script type=”text/javascript”> var mynum = 30; alert(“hello!” ); alert(mynum); </script> Result Message boxes are displayed in sequence 9. Confirm (Confirm message dialog box) The Confirm message dialog box is usually used to allow the user to make a choice, such as “Are you right?” And so on. Pop-up dialog box (including a OK button and A cancel button).
Grammar:
confirm(str); Parameter Description:
STR: Text to display in the message dialog box Return value: Boolean value The return value: Returns true when the user clicks OK Returns false when the user clicks the cancel button Note: What button can be determined by the return value
Look at the following code: <script type=”text/javascript”> Var myMessage =confirm(” Do you like JavaScript?” ); if(mymessage==true) {document.write(” Good, come on!” ); } else {document.write(“JS powerful, to learn oh!” ); } </script> 10. Ask questions (Prompt message dialog) Prompt displays a message dialog box, which is usually used to ask for information that you need to interact with the user. Pop-up message dialog box (containing a ok button, fetch Cancel button with a text input box).
Grammar:
prompt(str1, str2); Parameter Description:
Str1: Unmodifiable text to be displayed in the message dialog box Str2: the content in the text box can be modified The return value:
1. Click ok. The content in the text box will be returned as the function value 2. Click the Cancel button to return NULL Look at the following code:
Var myname=prompt(” please enter your name :”); if(myname! =null) {alert(” hello “+myname); } else {alert(” Hello my friend.”); } 11, Open new window (window.open) The open() method finds an existing or newly created browser window.
URL: An optional parameter that displays the URL or path of a web page in the window. If this parameter is omitted, or its value is an empty string, then the window Do not display any documents. Window name: Indicates the name of the open window. This parameter is optional. 1. The name consists of letters, digits, and underscores (_). 2. Names with “_top”, “_blank”, and “_self” have special meaning. _blank: Displays the target page in a new window _self: Displays the target page in the current window _TOP: displays the target page in the upper window of the frame page 3. Only one window with the same name can be created. To create multiple Windows, the name cannot be the same.
4. Name cannot contain Spaces. Parameter string: Optional parameter to set window parameters separated by commas. Parameter list: Top: number of pixels from the top of the window away from the top of the screen. Value: number Left: indicates the number of pixels left of the window away from the left of the screen. Value: digit Width: indicates the width of the window. Value: number Height: indicates the height of the window. Value: number Menubar: has a menu, value: yes,no or 1,0 Toolbar: does it have a toolbar,, value: yes,no or 1,0 Scrollbars: with or without scrollbars,, value: yes,no or 1,0 Status: does it have a status bar? Values: yes,no, or 1,0 Resize: indicates whether the size can be resized. Value: yes,no, or 1,0 Fullscreen: fullscreen, value: yes,no, or 1,0 For example: Open http://www.imooc.com in a new form, size 300px by 200px, no menu, no toolbar, no status bar, There are scrollbar Windows, 100 pixels from the top of the screen, 0 pixels to the left of the screen. :
<script type=”text/javascript”> window.open (‘http://www.imooc.com’,’_blank’,’width=300,height=200,top=100,left=0,menubar=no,toolbar=no, Status =no,scrollbars=yes’) </script> Note: Runtime results consider browser compatibility issues. 12, Close window (window.close) Close () closes the window
Usage:
window.close(); // Close this window or
< window object >.close(); // Close the specified window For example, close the newly created window.
<script type=”text/javascript”> var mywin=window.open(‘http://www.imooc.com’); // Store the new window object in the variable mywin mywin.close(); </script> Note: the above code opens a new window while closing the window, you can’t see the opened window. 13. Get to know DOM The Document Object Model (DOM) defines a standard way to access and process HTML documents. The DOM HTML text Files are rendered as a tree structure (node tree) with elements, attributes, and text. HTML documents are collections of nodes, three common TYPES of DOM nodes: 1, element node 2. Text nodes 3. Attribute node Such as: <a >JavaScript DOM</a> Element node: A Text node: JavaScript DOM Attribute node: 14. InnerHTML property The innerHTML attribute is used to get or replace the content of an HTML element.
Grammar:
Object.innerHTML Note:
1.Object is the element Object obtained, such as the element obtained through document.getelementById (“ID”).
2. Note the writing. InnerHTML is case sensitive.
15. Change the HTML style The HTML DOM allows JavaScript to change the style of HTML elements. How do I style an HTML element?
Grammar:
Object.style.property=new style; Note :Object is an element Object obtained, such as the element obtained via document.getelementById (” ID “).
Basic attributes use:
16. Show and hide (display attributes) Web pages often see show and hide effects, which can be set using the display property. Another display and hide property is visibility, with values visible and hidden, but unlike the display property, visibility hides the graph The position of the slice is not hidden, and the position of the image is also hidden when display is hidden. Grammar:
Object.style.display = value Note :Object is an element Object obtained, such as the element obtained via document.getelementById (” ID “).
Value the value: None: not shown (hidden) Block: displays as a block-level element For example: < script > function show(){ var mychar = document.getElementById(“con”); / / or the document. The getElementById (” con “). Style. The display = “block”; mychar.style.display=”block”; } function hide(){ var mychar = document.getElementById(“con”); mychar.style.display=”none”; } </script> 16. Control the className (className attribute) The className attribute sets or returns the class attribute of the element.
Grammar:
object.className = classname Function:
1. Get the class attribute of the element
2. Specify a CSS style for an element in a web page to change the appearance of that element
19. Operator priority: Arithmetic operator > Comparison operator > Logical operator > “=” assignment operator 20, Array: myarray.length; // Get the length of the array myarray, since the index of an array always starts at 0, so the upper and lower bounds of an array are: 0 and length – 1. The length of the array changes as the elements grow, Two-dimensional array: Elements are enclosed in brackets 20, switch statement: do not add break after the last default 21, Access string object method:
Use the String toUpperCase() method to convert a String from lowercase toUpperCase:
var mystr=”Hello world!” ; var mynum=mystr.toUpperCase(); After executing the above code, the value of mynum is: HELLO WORLD! Use the toLowerCase() method to change all uppercase letters of the string toLowerCase strings. 22, Date Date object Date objects can store any date and can be accurate to the millisecond (1/1000 of a second).
Define a time object:
var Udate=new Date(); Note: The first letter of the keyword new, Date() must be capitalized.
Makes Udate a date object with an initial value: the current time (current computer system time).
If you want to customize the initial value, use the following method: var d = new Date(2012, 10, 1); October 1, 2012 var d = new Date(‘Oct 1, 2012’); October 1, 2012 Access method syntax: “< date object >.< method >”
Common ways to handle times and dates in Date objects: Get /setDate() // Returns/sets the date Get /setFullYear() // Returns/sets the year as a four-digit number Get /setYear()// Returns/Sets the year Get /setMonth()// Returns/Sets the month, 0: January… Eleven: December, so add one Get /setHours()// return /setHours, 24 hours system Get /setMinutes()// Sets the number of minutes Get /setSeconds()// Returns/Sets the number of seconds Get /setTime()// return /setTime(in milliseconds) 24, returns the character at the specified position The charAt() method returns a character at a specified position. The returned character is a string of length 1.
Grammar:
stringObject.charAt(index) Parameters that Index: A required number representing a position in the string, that is, the index of a character in the string Note: 1. The subscript of the first character in the string is 0. The subscript of the last character is the string length minus one (string.length-1).
2. If index is not between 0 and String. length-1, this method returns an empty string. 24, returns the first occurrence of the specified string The indexOf() method returns the first occurrence of a specified string value in a string.
grammar
stringObject.indexOf(substring, startpos) Parameter Description: Substring: Required, specifying the string value to retrieve. This method will retrieve the string stringObject from beginning to end to see if it contains children String substring. Startpos: An optional integer parameter specifying the start of the search in the string. Its legal value is 0 to stringobjectLength-1, if Omiting this parameter searches from the prefix of the string and from the startpos position of stringObject for the substring, if not Parameters will be looked up from the start of stringObject. Note: 1. The indexOf() method is case sensitive.
2. If the string value to retrieve is not present, this method returns -1. 25, string split() Knowledge explanation:
The split() method splits a string into an array of strings and returns this array.
Grammar:
stringObject.split(separator,limit) Parameter Description: Separator: Required to split stringObject into two arrays with one separator on the left and one on the right Class. Limit: An optional argument, the number of times to split. No more substrings will be returned than the number specified by this argument Note: If you use the empty string (“”) as separator, each character in stringObject is separated. Substring () The substring() method is used to extract the character of a string intermediate between two specified subscripts.
Grammar:
stringObject.substring(starPos,stopPos) Parameter Description: StartPos: required, a non-negative integer, starting position StopPos: Optional, a non-negative integer, end position. If omitted, the substring returned will continue to the end of the string object Note:
1. Return all characters from start to stop-1. The length of the characters is stop minus start.
2. If the arguments start and stop are equal, the method returns an empty string (that is, a string of length 0).
3. If start is larger than stop, the method swaps these two parameters before extracting substrings. Select substr() from substr() The substr() method extracts a specified number of strings from the string starting at startPos.
Grammar:
stringObject.substr(startPos,length) Parameter Description: StartPos: Mandatory. The starting position of the substring to be extracted must be a numeric value Length: Optional, extracts the length of the string or, if omitted, returns characters from startPos to the end Note: The position from the end of the string if the parameter startPos is negative. That is, -1 is the last character in the string, -2 is the penultimate character, and so on.
If startPos is negative and the absolute value is greater than the string length, startPos is 0. 28. Math object Math object, which provides mathematical calculations of data.
Running results:
3.141592653589793 15 Note: The Math object is a native object, and without creating it, you can invoke all of its properties and methods by using Math directly as an object . That’s how it differs from Date String. Math object properties: E: Returns the arithmetic constant E, the base of the natural logarithm (approximately equal to 2.718) LN2: returns the natural logarithm of 2 (approximately 0.693) LN10: Returns the natural logarithm of 10 (approximately equal to 2.302) LOG2E: Returns the logarithm base 2 of e (1.442) LOG10E: Returns the logarithm base 10 of e (0.434) PI: Returns PI (3.141519) SQRT1_2: Returns the reciprocal of the square root of 2 (0.707) SQRT2: returns the square root of 2 (1.414) Math object methods: Abs (x): Returns the absolute value of x Acos (x): Returns the inverse cosine of x Asin (x): Returns the arcsine of x Atan (x): Returns the arctangent of x 29, round up ceil() The ceil() method rounds up a number.
Grammar:
Math.ceil(x) Parameter Description: X: the value that must be specified Note: it returns the nearest integer greater than or equal to x. For example: document.write(math.ceil (-5.9)) the result is: -5 30, take the whole floor() The floor() method rounds down a number.
Grammar:
Math.floor(x) Parameter Description: X: the value that must be specified Note: Returns the nearest integer that is less than or equal to x. 31, round() The round() method rounds a number to the nearest whole number.
Grammar:
Math.round(x) Note:
1. Return the nearest integer to x.
2. For 0.5, this method will be rounded up. (5.5 will be rounded to 6)
3. If x is equally close to the integers on both sides, the result is close to the numerical value in the +∞ direction. (If -5.5 is rounded to -5; -5.52 will be rounded to -6), 31, Random number random() The random() method returns a random number between 0 and 1 (greater than or equal to 0 but less than 1). Grammar:
Math.random(); Note: Returns a positive numeric value greater than or equal to 0 but less than 1. Get a random number between 0 and 10 :(math.random ()) *10 Array Array object An array object is a collection of objects that can be of different types. Each member object of the array has a “subscript”, which is used Represents its position in the array, starting from zero
Array definition methods:
1. Define an empty array:
Var Array name = new Array(); 2. Define an array with n empty elements:
Var Array name =new Array(n); When defining an array, initialize the data directly:
Var array name = [< element 1>, < element 2>, < element 3>… ; We define myArray and assign it as follows:
Array name [subscript] = value; Note: Array subscripts are enclosed in square brackets, starting at 0.
Array properties:
< array object >.length; Returns the length of the array, i.e. how many elements there are in the array. It’s equal to the last element in the array Add one to the subscript of theta.
Array methods:
Array concat() The concat() method is used to join two or more arrays. This method returns a new array, leaving the original array unchanged.
grammar
arrayObject.concat(array1,array2,… ,arrayN) Parameter Description: Array1: The first array to link . Arrayn: The NTH array to join
Note: This method does not alter the existing array, but only returns a copy of the concatenated array. Such as: <script type=”text/javascript”> var myarr1= new Array(“010”) var myarr2= new Array(“-“,”84697581”); document.write(myarr1.concat(myarr2)); // Not document.write(concat(myarr1, myarR2)); </script> Join () specifies a delimiter to join array elements The join() method is used to put all the elements of an array into a single string. Elements are separated by the specified delimiter.
Grammar:
ArrayObject. Join (separator) Parameter Description: Separator: Optional. Specifies the separator to use. If omitted, separate it with a comma
Reverse () The reverse() method is used to reverse the order of elements in an array.
Grammar:
arrayObject.reverse() Note: This method changes the original array and does not create a new one. 33, select element Slice () The slice() method returns selected elements from an existing array.
grammar
arrayObject.slice(start,end) Parameter Description: If it’s negative, it starts at the end of the array. -1 is the last element, -2 Is the penultimate element End: Optional, specifies where to end. If this parameter is not specified, all elements from start to the end of the array will be shard if it is negative Number, which specifies the element counting from the end of the array 1. Return a new array containing elements from the arrayObject from start to end (excluding that element).
2. This method does not modify the array, but returns a subarray. Note:
1. You can use negative values to pick elements from the end of an array.
2. If end is not specified, the slice() method selects all elements from start to the end of the array.
3. String.slice() is similar to array.slice (). Array sort sort() The sort() method sorts the elements in an array in a certain order.
Grammar:
Arrayobject.sort (method function) Parameter Description: Method functions: Optional, specify the sort order, must be functions 1. If < method function > is not specified, it is sorted in Unicode code order.
2. If < method function > is specified, the sorting method specified by < method function > is sorted. myArray.sort(sortMethod); Note: This function compares two values and returns a number indicating the relative order of the two values. The comparison function should take two arguments, a And b, which return the following values:
The return value <=-1 indicates that A precedes B in the sorted sequence. If the return value is >-1 && <1, it indicates that A and B have the same sort order. The return value >=1 indicates that A comes after B in the sorted sequence. Sorting function: sortNuM(a,b) <script type=”text/javascript”> function sortNum(a,b) { return a – b; // If (a – b) (b – a) (b – a) } var myarr = new Array(“80″,”16″,”50″,”6″,”100″,”1”); document.write(myarr + “<br>”); document.write(myarr.sort(sortNum)); < / script > / / the result is 80,16,50,6,100,1 and 1,6,16,50,80,100 JavaScript timer In JavaScript, we can execute code after a set interval, rather than immediately after a function is called. Timer type: One-time timer: Triggers only once after the specified delay time. setTimeout Intermittent trigger timer: triggers at regular intervals. setInterval SetTimeout and setInterval can be converted to each other, and another setTimeout call from setTimeout can produce the same value as setInterval role Such as: function display(){ . setTimeout(“display()”,1000); } Timer method: SetTimeout ()// To execute code after the specified delay ClearTimeout ()// Unset setTimeout Setinterval ()// Executes the code at specified intervals Clearinterval()// Unset setInterval () The timer setInterval () At execution time, the code executes at specified intervals after the page has been loaded.
1. Code: function to be called or code string to be executed.
2. Interaction time: The interval between the periodic execution or invocation of an expression, in milliseconds (1s=1000ms).
The return value:
A value that can be passed to clearInterval() to cancel periodic execution of the code.
Call function format (assuming there is a clock() function): setInterval(“clock()”,1000) or setInterval(clock,1000) Cancel the timer clearInterval() The clearInterval() method cancels the interaction time set by setInterval().
Grammar:
clearInterval(id_of_setInterval) Parameter Description: Id_of_setInterval: ID returned by setInterval().
The clock() function is called every 100 milliseconds and displays the time.
34, timer setTimeout() SetTimeout () timer that executes an expression only once after a specified post-load delay.
1. The function to call or the code string to execute. 2. Delay time: time to wait before executing the code, in milliseconds (1s=1000ms). ClearTimeout () SetTimeout () is used with clearTimeout() to stop the timer.
Grammar:
clearTimeout(id_of_setTimeout) Parameter Description: Id_of_setTimeout: ID value returned by setTimeout(). This value identifies the block of code to cancel deferred execution.
35, the History object The history object records the pages (urls) that the user has visited and enables the browser to navigate backwards and forwards in a similar way.
Note: Every browser window, every TAB, and even every frame has its own history object from the moment the window is opened Specific Window object association.
Grammar:
[properties | methods] window. The history. Note: Window can be omitted. History object property Length: Returns the number of urls in the browser history list History object method Back (): load the previous URL in the history list //window.history.back() equivalent to window.history.go(-1) Forward () : a url after the loading history list window. / / the history. The forward () is equivalent to the window. The history. The go (1) Go (): loads a specific page in the history list 36. Return to other pages in your browsing history The go() method loads a specific page in the history list, depending on which page you are currently on.
Grammar:
window.history.go(number); Parameters: 1: Next page, go(1) is equivalent to forward () 0: current page, -1: Previous page,go(-1) is equivalent to back () Other values: Relative position of the URL to be accessed in the list of urls in History In the browser, return to the second history page before the current page, the code is as follows:
window.history.go(-2); Note: This is the same as clicking the back button twice in the browser.
Similarly, return to the third history page visited after the current page, the code is as follows:
window.history.go(3);
Window. The screen. The properties Object properties: AvailHeight: The screen height, in pixels, that the window can use AvailWidth: The screen width available for the window, in pixels ColorDepth: The number of color bits represented by the user’s browser, usually 32 bits (bits per pixel) PixelDepth: The color number represented by the user’s browser, also 32 bits (bits per pixel) (IE does not support this property) Height: The height of the screen, in pixels Width: indicates the screen width, in pixels 39. High and wide screen resolution The window.screen object contains information about the user’s screen. 1. Screen. height Returns the high screen resolution 2. Screen. width Returns the width of the screen resolution Note: 1. Units are in pixels. 2. Window.screen objects can be written without the window prefix. DOM: Document object Model There are three types of DOM: Core DOM, XML DOM, and HTML DOM Now I’ll focus on the HTML DOM DOM node operations have four main parts: Add: createElement(), appendChild(), insertBefore(), cloneNode() Delete: removeChild(); Change: Change the attribute: setAttribute()/ object name. The property name Change content: innerHTML,innerText Check: getElementById (), getElementsByName (), the getElementsByTagName (), parentNode, firstChild, lastChild, GetElementsByName () method Returns a collection of node objects with the specified name.
Grammar:
document.getElementsByName(name) Unlike the getElementById() method, elements are queried through their name attribute, not through their ID attribute.
Note:
1. Because the name attribute in the document may not be unique, all getElementsByName() methods return an array of elements instead of one Elements.
2. Like array also has the length property, can be accessed in the same way as the array, starting from 0. 41, the getElementsByTagName() method Returns a collection of node objects with the specified label name. The order in which elements are returned is the order in which they appear in the document.
Grammar:
getElementsByTagName(Tagname) Description:
1. Tagname indicates the Tagname, such as p, a, and img.
2. The length property can be accessed in the same way as the array, so it starts at 0. Such as: function getTagElements() { var myI=document.getElementsByTagName(“input”); alert(myI.length); } 41, the difference between the getElementByID getElementsByName, getElementsByTagName People, for example, have identification cards, names, categories (adult, child, old), etc.
1. ID is a person’s ID number, which is unique. So you get the specified person by getElementById.
2. Name is his Name. So get the set of people with the same name through getElementsByName.
3. TagName can look like a class, and getElementsByTagName gets a collection of people of the same class. People like kids, GetElementsByTagName (” child “).
42, the specified value.
Grammar:
elementNode.setAttribute(name,value) Sometimes change the attributes of a node, you can also use elementNode. AttributeName = “XXXX”, namely the object name. The property name Description:
1. Name: Indicates the name of the property to be set.
2. Value: Indicates the value of the attribute to be set.
Note:
1. Set the specified property to the specified value. If no property with the specified name exists, the method creates a new property.
2. Similar to the getAttribute() method, the setAttribute() method can only be called by the element node object. Node properties In the Document Object Model (DOM), each node is an object. DOM nodes have three important properties:
1. NodeName: indicates the nodeName
2. NodeValue: specifies the nodeValue
3. NodeType: indicates the nodeType
NodeName: the name of the node, which is read-only.
1. The nodeName of the element node is the same as the label name 2. The nodeName of the property node is the name of the property 3. The nodeName of the text node is always #text 4. The nodeName of the document node is always #document
NodeValue: specifies the nodeValue
1. The nodeValue of the element node is undefined or null 2. The nodeValue of a text node is the text itself 3. The nodeValue of the attribute node is the value of the attribute
NodeType: specifies the type of the node. There are several common node types:
Element Type Node type Element 1 Property 2 Text 3 Note 8 Document 9 43. Access childNodes Returns a list of all children of the selected element node, which can be viewed as an array with the length attribute.
Grammar:
elementNode.childNodes Note:
If the selected node has no child nodes, this property returns the NodeList that does not contain the node. Accesses the first and last items of the child FirstChild is the firstChild to occur, and lastChild is the lastChild to occur FirstChild returns the firstChild of the array ‘childNodes’. This property returns if the selected node has no children NULL.
Grammar:
node.firstChild Note: Has the same effect as elementNode.childNodes[0].
LastChild returns the lastChild of the array ‘childNodes’. This property returns if the selected node has no children NULL.
Grammar:
node.lastChild Description: with elementNode..childnodes [elementNode..childnodes. Length – 1) is the same effect.
Note: In the previous section, we learned that Internet Explorer ignores empty text nodes generated between nodes, while other browsers do not. we You can filter child nodes by detecting node types. (Explained in later chapters) 44. Access parentNode Gets the parent of the specified node
Grammar:
elementNode.parentNode Note: There can only be one parent node.
Take a look at the following example to get the parent of the P node as follows:
<div id=”text”> <p id=”con”> parentNode Gets the parent of the pointing node </p> </div> <script type=”text/javascript”> var mynode= document.getElementById(“con”); document.write(mynode.parentNode.nodeName); </script> Running results:
ParentNode obtains the parentNode of the pointing node DIV Access the ancestor node:
elementNode.parentNode.parentNode 44. Access the sibling node 1. The nextSibling attribute returns the nodes immediately following a node (in the same tree hierarchy).
Grammar:
nodeObject.nextSibling Note: If there is no such object, this property returns NULL.
2. The previousSibling attribute returns the nodes immediately following a node (in the same tree hierarchy).
Grammar:
nodeObject.previousSibling Note: If there is no such object, this property returns NULL.
Note: Both attributes fetch nodes. Internet Explorer ignores empty text nodes (for example, newlines) generated between nodes, while Other browsers won’t ignore it. 45 insert node appendChild() Adds a new child node after the last list of children of the specified node.
Grammar:
appendChild(newnode) Parameters:
Newnode: specifies the node to be added. Such as: var otest = document.getElementById(“test”); var newnode=document.createElement(“li”); newnode.innerHTML=”PHP”; otest.appendChild(newnode); InsertBefore () The insertBefore() method inserts a new child before an existing one.
Grammar:
insertBefore(newnode,node);
Parameters:
Newnode: indicates the newnode to be inserted.
Node: specifies the node to be inserted before this node. Note: otest. InsertBefore (newnode node); Otest.insertbefore (newNode,otest.childNodes[0]); RemoveChild () The removeChild() method removes a node from the child node list. If the node is deleted successfully, this method returns the node. If the node fails, this method returns the node Back to NULL.
Grammar:
nodeObject.removeChild(node) Parameters:
Node: Required, specifies the node to be deleted. Such as: function clearText() { var content=document.getElementById(“content”); for(var i=content.childNodes.length-1; i>=0; i–){ var childNode = content.childNodes[i]; content.removeChild(childNode); } } ReplaceChild () ReplaceChild implements child node (object) replacement. Returns a reference to the replaced object.
Grammar:
node.replaceChild (newnode,oldnew ) Parameters:
Newnode: Required, object used to replace oldNew. Oldnew: Required, object replaced by newNode. <script type=”text/javascript”> function replaceMessage(){ var newnode=document.createElement(“i”); var newnodeTest=document.createTextNode(“JavaScript”); newnode.appendChild(newnodeTest); var oldNode=document.getElementById(“oldnode”); oldNode.parentNode.replaceChild(newnode,oldNode);
} Create the element node createElement The createElement() method creates an element node. This method returns an Element object.
Grammar:
document.createElement(tagName) Parameters:
TagName: String value used to specify the type of element to be created.
Note: To be used in conjunction with the appendChild() or insertBefore() methods, display the element in the page. 48, Create the text node createTextNode The createTextNode() method creates a new Text node and returns the newly created Text node.
Grammar:
document.createTextNode(data) Parameters:
Data: string value that specifies the text of this node. 50, the size of the browser window viewable area Get the size of the browser window (the viewport of the browser, excluding toolbars and scrollbars) :
For IE9+, Chrome, Firefox, Opera, and Safari:
• Window.innerheight – The internal height of the browser window
• window.innerwidth – the innerWidth of the browser window
Ii. For Internet Explorer 8, 7, 6, 5:
• document. DocumentElement. ClientHeight said HTML document in the current height of the window.
• document. DocumentElement. ClientWidth said HTML document in the current width of the window.
or
The body attribute of the Document object corresponds to the <body> tag of the HTML Document
• document. Body. ClientHeight
• document. Body. ClientWidth
JavaScript schemes that work in different browsers:
var w= document.documentElement.clientWidth || document.body.clientWidth; var h= document.documentElement.clientHeight || document.body.clientHeight; Onscroll =function(){} 50, web page size scrollHeight ScrollHeight and scrollWidth, get the height and width of the web page content.
If the oDiv is inside the viewable area: Coordinates of the viewable area from the top of the page, the distance from the top of the page to the viewable area: Var scrollTop = document. DocumentElement. ScrollTop | | document. The body. The scrollTop; ScrollTop +oDiv distance to the top of the viewable area, that is: scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2
var sw=document.documentElement.scrollWidth || document.body.scrollWidth; I. For IE and Opera:
ScrollHeight is the actual height of the web page content, which can be smaller than the clientHeight.
2. For NS and FF:
ScrollHeight is the height of the page content, but the minimum value is clientHeight. That is to say, the actual height of the web content is smaller than clientHeight , scrollHeight returns clientHeight.
Third, browser compatibility
var w=document.documentElement.scrollWidth || document.body.scrollWidth; var h=document.documentElement.scrollHeight || document.body.scrollHeight; Note: case sensitive
ScrollHeight and scrollWidth also get the actual height and width of the content in the Dom element. 51, page size offsetHeight OffsetHeight and offsetWidth, get the height and width of the page content (including edges such as scroll bars, which change with the display size of the window).
A, values,
OffsetHeight = clientHeight + scroll bar + border.
Second, browser compatibility
var w= document.documentElement.offsetWidth || document.body.offsetWidth; var h= document.documentElement.offsetHeight || document.body.offsetHeight;
function display(){ } window.onload=display; // Note that this is not display(), if display(a) has parameters, it is another matter, can use anonymous function </script> Window.onload =function(){display(); } Table Table object: Attributes of the Table object: Rows [] : all rows, forming an array, InsertRow (index); deleteRow(index) TableRow: one line The TableRow object has two properties, ceils[] and rowIndex Ceils []: All cells in a row, forming an array RowIndex means to return the position of the row in the table, starting at 0 Common methods: InsertCeil (index): Inserts a cell at a specified position in a row DeleteCeil (index): Deletes the cell specified in the row TableCeil: A cell There are three properties: CeilIndex: Returns the position of the cell InnerHTML: The HTML that sets or returns a cell ClassName: Sets or returns the class attribute of the element For TableCeil objects, its properties are used primarily Cascading menu: For example, when selecting a province, the cities for that province are displayed on the right Array: There are two ways to read an array: 1. For loop 2 var fruit=new Array(“apple”,”orange”,”peach”,”banana”); For (var x in fruit){// var x in fruit document.write(fruit[x]+”<br/>”); } Drop-down menu: The SELECT tag, which contains three properties, 1) Options property, is an array of options options[], used to return all options in the drop-down menu. Create option: var option=new option (display text, value) 2) length: total number of options 3) selectedIndex: index number of the selected option Common methods: Add (Option object, add position), // The add position can be null, indicating that the add is at the end Common events: Onchange: triggered when options are changed Mouse becomes hand shape: Cursor: pointer; List-style :none; <a></a> The form of the function triggered when the link is clicked is the A tag: <a href=”javascript:show()”>… </a> When the picture is set to absolute positioning: To the right is positive, to the down is positive; Set the image of a location on the page to float as the scroll bar moves: 1) Place the image in the div and set the absolute position to float on the page 2) When the mouse is rolling, the top and left coordinates of the picture will change 3) Obtain the mouse scrolling distance, scrollTop (the scrolling distance of the scroll bar or the longitudinal distance from the X-axis to the scroll wheel), scrollLeft (the scrolling bar direction The distance to the left or the horizontal distance from the y axis to the wheel) 4) Use the mouse scroll event onScroll event to call the function to move the div position: onScroll () Style The style in which the object is positioned: Left, top: upper left corner -Leonard: Right, bottom right Position: Absolute, relative, static (fix) // The position takes effect only when the position is set to absolute or relative Z-index: stack order To use pixel values representing element positions, use parseInt to convert integers: Var c=parseInt (a) +parseInt (b) + “px”; Gets or sets the coordinates of the element: Internet Explorer: Use only currentStyle objects Firefox: use getComputedStyle (); Document. The defaultView. GetComputedStyle (element object, null). attribute Get the document object (root node) : the HTML tag Var a = document documentElement, / don’t have to the body, because/because some browsers are not compatible Window.onload = function name; // Note that the function is not parenthesized Window. onscroll= function name; ???? The option in the drop-down menu stays in question ?????? 1. Classes: javascript is a prototype-based language. There are no declarations of classes, such as c++ and Java Defining a class is as simple as defining a function, such as Function Person(){} or var Person=function(){} 2, Object (class instance) : function Person(){} var person1=new Person(); var person2=new Person();