Dom&bom notes

Source: Internet
Author: User

Day01
Schoolboys
1. Dom Overview
2. ***dom Tree
3. * Find

1. DOM Overview:
DHTML: A generic term for dynamic web technologies
Dhtml=html+css+js
Despised questions:
HTML XHTML DHTML XML:
HTML: Hypertext Markup Language, language that specializes in writing web content
XHTML: A strict HTML language standard
DHTML: A general designation of Dynamic Web technologies, =HTML+CSS+JS
XML: Extensible Markup Language, customizable labels
Designed to store/transfer self-describing structured data
is gradually replaced by JSON.
< actors >
< name > Fan Bingbing </name >
< math >91</Math >
< Chinese >65</language >
< English >95</English >
</actor >
"{" name ":" Fan Bingbing "," math ":",... " --json

BOM VS DOM
BOM: Browser object model (API), an API that specializes in manipulating browser windows
No standard!
DOM: Document Object Model (API), an API that specializes in manipulating web content
You can make any changes to any object in the Web page!
Dom is standard, more than 90% browsers are strictly compatible

Core DOM: Common API for manipulating all structured documents (xml,html)
HTML DOM: A simplified API for HTML documents
The HTML DOM doesn't do all the work, and the real development is that the core DOM works with the HTML DOM.

HTML DOM: Everything in a Web page is an object (element, attribute, text)
All objects in the same Web page, in memory, are connected to each other, forming a DOM tree.

2.***dom Tree:
Each element, attribute, text, and comment in the document is considered a node object--node--all
The parent type of the node object
When a page is loaded into memory, the browser creates a Document object for the page. All node objects are
is a child node of the Document object.
Document, which encapsulates the addition, deletion, and lookup of all child nodes in a Web page

The node type defines 3 public properties:
NodeType: Numeric value of the type of the node
When to use: specifically used to determine the type of node obtained
If it is an element node, return 1
If it is a text node, return 3
NodeName: Name of the node
When to use: specifically used to determine the name of a given tag
Returns the label signature if it is an element node
* * Emphasis: nodename return all uppercase sign
If it is a text node, return #text

NodeValue: The value of the node:
element node, return null
Text node that returns the contents of the text

ChildNodes: Get all child nodes under the current node object
Class Array object, [i]. length

DOM Tree 6 Relationships: 6 Properties:
Father and son: 4: parentnode childNodes firstchild LastChild
Brother: 2: previoussibling nextSibling

Pm:
Review:
1. Dom Tree:
Node tree: Every element, attribute, text, and comment in a Web page is a node object
All node objects in the same Web page form a tree structure through parent-child relationships
Root: Document Object
Node points: Relationship between nodes: 6 properties
Parent-Child Relationship 4 kinds: parentnode childNodes firstchild LastChild
Brotherly relationship 2 kinds: previoussibling nextSibling

ChildNodes: Class Array Object,
Dynamic Collection * * *: You do not save any actual data
Find it again every time you use it
for (Var i=0;i<parent.childnodes.length;i++) X
for (Var i=0,len=parent.childnodes.length;i<len;i++)


Schoolboys
1. * * * * Traversal:
2. * Find

1. * * * * traversal: Starting from the specified parent element, according to the principle of depth first
Traverse all levels of child nodes
2 steps:
1. Define a function to find all the immediate child nodes under any parent node
2. In the principle of depth first, the function itself is called recursively

When to use recursive calls: 2 scenarios:
1. When traversing a tree structure with an indeterminate level of depth *:
For example: elements in a Web page, folder structure of the network disk
2. * Multilevel management structure with indeterminate level depth *:

Element tree: A tree structure that consists only of element nodes
There is actually a set of element tree attributes corresponding to the 6 properties of the node tree

Node Tree element tree
Parent Object ParentNode Parentelementnode
All sub-objects ChildNodes children
First sub-object FirstChild firstelementchild
Last sub-object LastChild lastelementchild

A former brother PreviousSibling previouselementsibling
After a brother NextSibling nextelementsibling

When to use: As long as you want to traverse element nodes only, use the element tree
Issue: IE8 not compatible, children available

DOM LEVEL2 Traversal Api:2--the choice of learning
1. Depth-First traversal: Nodeiterator
Node iterator
How to use: 2 steps:
1. Create a Traverse API object:
var iterator=document.createnodeiterator (
Begins the parent node object,
Whattoshow,
Null,false
);
WhatToShow:NodeFilter.SHOW_ELEMENT
Nodefilter.show_all
2. Repeatedly call the Iterator.nextnode () method with the while loop

Emphasis: 1. Once NextNode (), move to the next
2. Iterator.previousnode (), Back once
Job: To iterate over the result for Nodeiterator, add indentation

2. Own traversal: TreeWalker:
Use almost the same, but treewalker more than iterator individual methods

Summary: 4: Tree of Node tree elements
API (Nodeiterator,treewalker)

2. * Find: 5 APIs:
1. Search by ID:
var Elem=document.getelementbyid ("id value");
2. Search by Tag name: (The main means of climbing down the tree)
var elems=parent.getelementsbytagname ("tag name");
Elems is also a dynamic collection * * *
* Not only the direct sub-nodes, but also the indirect sub-nodes can be obtained *
3. Find By Name property: (specifically for finding elements in a form)
var elems=parent.getelementsbyname ("Name attribute value");
Elems is also a dynamic collection * * *
4. Press ClassName to find
var elems=parent.getelementsbyclassname ("Class attribute")

Elems: Dynamic collection, re-locating each time it is used
for (Var i=0,len=elems.length;i<len;i++)

5. The core of Selector Api:jquery
var elem=parent.queryselector ("selector");
var elems=parent.queryselectorall ("selector");
2 Features: 1. Built-in API: High execution efficiency
2. Elems: A collection containing full object properties
will not be searched repeatedly!

Day02
Review:
1. Everything in the DOM is a Node object: nodes Type
Elements Node object: element type
Text Node object: text Type
Three main properties: NodeName nodeType NodeValue

Six relationships: ParentNode childNodes firstchild LastChild
PreviousSibling nextSibling

Two trees: Tree of Node tree elements

2. * * * * Traverse: 4 Kinds: Default is * Depth First *
1. Traversing the node tree-handwritten, with indentation
2. Traversing the element tree-handwritten, with indentation
3. Nodeiterator:nextnode () Previousnode ()
4. TreeWalker:
3. * Find: 5 kinds:
1. Var Elem=document.getelementbyid ("id value");
2. var elems=parent.getelementsbytagname ("tag name");
3. Var elems=document.getelementsbyname ("name attribute");
4. Var elems=parent.getelementsbyclassname ("Class attribute")
Elems: Dynamic collection, re-locating each time it is used
for (Var i=0,len=elems.length;i<len;i++)

5. The core of Selector Api:jquery
var elem=parent.queryselector ("arbitrary selector");
var elems=parent.queryselectorall ("arbitrary selector");
Can only be looked down from the parent node.
To find a peer: first parentnode upward, then queryselector downward

Elems: A collection of complete objects that contain all properties and methods
for (Var i=0;i<elems.length;i++)


Schoolboys
1. * Modify the contents or attributes of the element: 3 Kinds of things:
1. Content of elements
2. * * Attributes/attributes of the element
3. The style of the element: 2 places:
1. Modify the inline style
2. * Modify CSS rules in style sheets

1. Get or modify element content: 3 Properties:
1. InnerHTML: Gets/sets the HTML text between the start and end tags of the element
When to use: as soon as you get the original HTML content
Fixed routines: 2:
1. Delete all child elements under the parent element:
Parent.innerhtml= "";
2. Bulk replace all child elements under the parent element
Parent.innerhtml= "HTML for all child element tags" such as:
Ul.innerhtml= "<li> Movies </li><li> episodes </li>"
2. Textcontent/innertext: Get the start and end tags
Dom Standard IE8 Plain text content with no tags
When to use: whenever you want to remove a label, just get the text

3. Content of the text node: nodevalue

Pm:
Schoolboys
1. Element content
2. * * Element properties: Standard Custom
3. Element styles: CSS rules in inline style style sheets

1. Element content:
2. * * Element attribute: Get/set/has/removeattribute ()
All elements have the Attributes property, [i] access each property--understand
Read properties: 4 ways:
1. element.attributes[Subscript].value

2. Var value=element.attributes[' property name ']
3. Element.getattributenode (' attribute name '). Value
4. var value=element.getattribute ("attribute name")
When to use: Just get the value of any property

Modified properties: 2 kinds:
1. Element.setattribute (name, value);
IE8 not supported
Only: element.attributes[' property name ']=value
2. Element.setattributenode (Attrnode);

Remove attributes: 2:
1. Element.removeattribute (' attribute name ');
2. Element.removeattributenode (Attrnode);

Determine if an element contains attributes: 2:
1. Element.hasattribute (' property name ')//true or False
2. Element.hasattributes ();

Property vs Attribute
Attribute HTML attributes
Property: The properties that the object stores in memory
Use. Access
Attribute: The HTML attributes and custom attributes defined by the element object in the start tag

When accessing HTML standard properties. The two are exactly the same:
For example: <a href= "http://tmooc.cn" ...
A.href--> Property-->html DOM
A.getattribute ("href")-and features--core DOM

If you access custom properties, they are not universal!
<li/*data-age= "*/>eric</li>"
Read Custom properties: Li.data-age? X
Li.getattribute ("Data-age");
Set custom Properties:li.age=29--> Web page?
Li.getattribute ("age") not found;
Li.setattribute ("Data-age", 29);

3. * The style of the element:
1. Where is the style to be modified?
2. Priority level

1. Get or modify the inline style: Style object
The Style property set in the Style object has the highest priority!
Settings: Style. Property name = "Value"
Removed: 2 kinds:
Style. Property name = "";
Style.removeproperty ("CSS property name")
Problem: Only inline styles defined in the Style property can be manipulated
Unable to get or set style in style sheet

2. Get or modify properties in a style sheet: internal external ()
3 steps:
1. Get the style sheet object you want to modify:
var sheet=document.stylesheets[i];
StyleSheets: Get all style sheet objects for the current page
2. Obtain the Cssrule to be modified:
Cssrule: A curly brace in a style sheet is a Cssrule object
var cssrule=sheet.cssrules[i]
Cssrule may be nested.
3. Get the attributes in Cssrule
Cssrule.style. Property name

If the subscript is affected during traversal, it is recommended to traverse from backward to forward
To convert a class array object to a standard array: lis = Array.prototype.slice.call (LIS);

DAY03:
Schoolboys
1. * Create and DELETE nodes
2. *html Dom Common object: Table Select

1. * Create and DELETE nodes
1. Create a node:
To create an element node: 3 steps:
1. Create an empty element object:
var newelem=document.createelement ("tag name");
For example: Var a=document.createelement ("a");
<a></a>
2. Set the necessary properties:
Newelem. Property name = "Value";
Newelem.innerhtml= "Text";
For example: a.href= "http://tmooc.cn";
A.innerhtml= "Go to Tmooc";
<a href= "http://tmooc.cn" >go to Tmooc</a>
3. Mount the element object under the specified parent element: 2 kinds:
Added: Parent.appendchild (Newelem);
Emphasis: Only new nodes are appended to the parent element that is already in the page, resulting in rendering
For example: Div.appendchild (a);
<div>
...
<a href= "http://tmooc.cn" >go to Tmooc</a>
</div>

2. Create a document fragment: DocumentFragment
Document fragment: Storage space for temporary storage of multiple child nodes in memory
When do I use a document fragment? Append multiple peer elements repeatedly
WORKAROUND: First append all of the lateral elements to the document fragment
Append a document fragment to a parent element at once
* Document fragment does not participate in Append *

Pm:
Schoolboys
1. * Create and DELETE nodes:
2. * Common HTML DOM objects

1. * Create, Delete:
Insert new element: Parent.insertbefore (Newelem,oldelem);
Delete node: Parent.removechild (Oldelem);
OldElem.parentNode.removeChild (Oldelem);
Replacement node: Parent.replacechild (Newelem,oldelem);

Classroom Exercise: Cascading drop-down list:
1. onchange: Triggers when content changes
2. Select object: SelectedIndex property: Subscript for the currently selected item

2. * Common HTML DOM objects: Table Select Form
Table object:
Property:
THead TFoot tbodies
Rows: Get all row objects in table
Rows[i]: Get a Row object for the table medium and small label I
Method:
var newrow=insertrow (RowIndex):
RowIndex write-1, which means append at the end
For example: InsertRow (-1)
Core Dom:var Newrow=document.createelement ("tr")
Table.appendchild (NewRow)
DeleteRow (RowIndex):
For example: CurrRow.parentNode.removeChild (Currrow);
Table.deleterow (Currrow.rowindex)

TableRow object: Represents one of the TR objects in a Table object
A collection of table.rows that is a set of TableRow objects
Property:
Cells: All TD objects in the current line
Cells[i]: Gets the TD that is labeled I in the current line
RowIndex: The subscript position of the current row, specifically for deleting rows
Method:
var Newcell=insertcell (Index)
For example: InsertCell (3)
Core Dom:var Td=document.createelement ("TD");
Tr.appendchild (TD);
Deletecell (Index)
TableCell object:
Property: CellIndex


Select object:
Property:
Options: Get all option under current Select
Options[i]: Gets the option under the current select I position
SelectedIndex: Gets the subscript for the currently selected option
Method:
Add (new Option object)
For example: Select.appendchild (newopt);
Select.add (newopt);
Remove (Index)
Option object: Refers to an OPTION element under Select
How to create: Var newopt=new Option (Innerhtml,value)
To create an option object at the same time, set the innerHTML and Value properties of the object
Equivalent to: Var newopt=document.createelement ("option");
Newopt.innerhtml= "Content"
Newopt.value= "Value";

Sentence: Create, set, append
Select.add (New Option (Innerhtml,value));

Property: Index: Gets the subscript position of the current option, specifically for deleting
Selected: can be used as bool
Returns true if the current option is selected
Otherwise, returns false

Form object:
How to find a Form object
var form=document.forms[i/name];
How to find a data acquisition element in a form:
var elem=form.elements[i/name]

Event: onsubmit: Automatically triggered before formally submitting the form

Formula: tdsalary.innerhtml = "&yen;" + emp[i].salary.tofixed (2);


DAY04:
Review:
1. Form object:
How to find: document.forms[serial number |name]
How to find the elements of data acquisition:
document.forms[ordinal |name].elements[serial number |name]

To get or lose focus on an element: Elem.focus ()
Elem.blur ()

Get/Lose Focus event: onfocus onblur

Get the element that is currently getting focus: document.activeelement

Event: OnSubmit is automatically triggered before the form is formally submitted
Perform validation on the entire form
Form.onsubmit=function () {
As long as any one of the validations does not pass,
*:2 steps to cancel the event:
1. Get the Event object e:
var e=window.event| | Arguments[0];
if (E.preventdefault) {
E.preventdefault ()//dom
}else{
E.returnvalue=false//IE8
}
}

Form submission: 2 kinds: Directly click the Submit button;
If any of the elements in the current form have the focus, you can press ENTER to submit automatically
As long as the automatic form submission, the onsubmit will be triggered first, can be verified

Schoolboys
1. *bom:
Window object
Timer--Animation
2. Common BOM objects:
Navigator

1. BOM: An object that specializes in manipulating the browser window
Window object: 2 characters:
1. act as a global object!
2. Include BOM common objects

Property:
Size and Position:
Innerheight/width: Size of document display area
Outerheight/width: Window Size

pageYOffset: The distance from the upper-left corner of the document to the upper-left corner of the document display

1. Open new Link: 4 effects:
1. Open a new link in the current window to rewind
Html:
Js:[window.] Open ("url", "_self")
2. Open a new link in the current window, no back
Js:location.replace ("New url");
3. Open a new link in a new window, you can open multiple
Html:
Js:
4. Open a new link in a new window to open only one
Target--> the name of the target window
_self: Automatically get the current window name
_blank: Create a new window, randomly generate a duplicate name
* Window name: The same window name in memory can only open one
Will replace the first open
HTML: <a href= "xxx" target= "Custom window name" ></a>
Window.name= "Custom window name" JS:

Pm:
Schoolboys
1. Window object:
Window size and positioning
Timer

1. Window size and positioning:
Size:
1. Window.innerheight/width: Document display area width height
Outerheight/width: Width of the entire window

2. Screen.height/width: Desktop full resolution width high
Screen.availheight/availwidth: Remove the width of the remaining resolution after the taskbar

3. Sizing: Window.resizeto (width,height)
Adjusted to
Resizeby (variable width, height of change)

Position:
1. Upper left corner x coordinate: window.screenleft| | Window.screenx;
Y coordinate: window.screentop| | Window.screeny;
2. Move the window to the specified coordinates: window.moveto (x, y)
3. When an event occurs, the mouse is relative to the entire screen's coordinates:
Event.screenx|screeny

2. * * * * Timer: Allow the browser to perform the same task repeatedly at specified intervals
2 Kinds:
Recurring timer: Let the browser perform the same task repeatedly at specified intervals
If you do not stop manually, repeat
Disposable Timer: Let the browser wait for a period of time, perform a task
Auto Stop.
At the end of the one-time timer, reboot a disposable timer
Recommendation: Try to use one-time timers instead of periodic timers

How to use: Periodic and disposable usage exactly the same
Periodicity: 3 things:
1. The task to be performed for each step of the animation (function object)
function Step () {
What to do every step of the way
}
2. Put one-step task into the timer and call repeatedly
Timer=setinterval (step, interval of milliseconds)
3. You must use global variables to temporarily store the timer's number
Clearinterval (timer);
Timer = null;//These two sentences are almost synchronous.

Disposable: 3 Things
1. The task to be performed for each step of the animation (function object)
function Step () {
What to do every step of the way
/* Determine if it is necessary to continue to start the next timer based on conditions */
/* If the continuation condition is not met, empty Timer:timer = null*/}
2. Put one-step task into the timer and call repeatedly
Timer=settimeout (step, interval milliseconds | Number of milliseconds to wait)
3. You must use global variables to temporarily store the timer's number
Cleartimeout (timer)
Stop the timer that is waiting


DAY05:
Review:
1. Timers
Disposable Timers: 3 things:
1. * * * Every task to be performed * * *
End of task function: Decide whether to continue to start the next time
2. Put the task function into the timer automatically and repeatedly
Timer=settimeout (Task function, time interval)
3. Stop timer: 2 words:
Cleartimeout (timer)
Timer=null;

Schoolboys
1. Common BOM object: Navigator
2. * * * Event:
3. Cookies:

1. Common BOM objects:
1. Navigator: Object that holds browser configuration information
Cookieenabled: Determines whether cookies are enabled for the current browser
Plugins: Save a collection of all plug-in objects
UserAgent: A string that holds the browser name, version number

Pm:
Schoolboys
1. Window Common Sub-object: History Location screen
2. * * * Event
3. Cookies

1. Window Common sub-objects:
History:window The history stack of the URL that the current form has visited in the object
History.go (1): 1 times forward
Go (-1): Back 1 times
Go (0): Refresh the current page
Go (N): forward/Backward n times

Location: The URL address object that the current window is opening
Location.search: Get the query string in the URL
What if we get parameter names and parameter values further?
First press & separate, then press = to separate
Location.replace ("New URL"): Opens a new link in the current window
Do not retreat
(The old URL in history was replaced by the new URL)

Use location to open a new link in the current window, back: 2 kinds:
location.href= "New url";
Location.assign ("New url");

Refresh: Location.reload ();

Screen: Encapsulates display information for the current screens
Screen.height/width: Finish screen Width height
Availheight/width: Remove the remaining width height after the taskbar
Window7 the taskbar is transparent

2. * * * Event:
Changes in the state of objects triggered automatically by the browser or manually triggered by the user
DOM Level2 Event Standard
IE8: Self-made system!
Event handlers: Functions that are automatically executed when an event is triggered
For example: <button onclick= "function/js statement" ></button>
Btn.onclick ();

Event handling:
1. Event definition (Binding event handler): 3 kinds
HTML: < tag on event name = "Fun ()" >
D1.onclick=function () {
Eval ("Fun ()");
[Window.] Fun ();
}
Emphasis: Fun () in This-->window
If the current target element object is obtained:
html:onxxx= "Fun"
When defining functions in JS: Fun (Elem)


Js:elem.on Event name = function object;
An event handler for an element that binds only one function object
Dom Standard: Elem.addeventlistener (
"Event name", function object, whether triggered during capture phase)
True/false
An event handler function for an element that can add multiple different function objects IE8:elem.attachEvent
("On Event name", function object)
Actual execution: Elem.on event name (); This-->elem
2. * * * Event cycle: From the browser capture to the event, until the last event triggered, the process of experience

DOM Standard: 3 stages:
1. (from outside) Capture: start at the outermost HTML element, and record each layer of element bound events
function. Until the target element
2. Target trigger: Automatic execution of the event handler function bound on the target element
3. (Out-of-the-inside) events bubble: From the parent element of the target element, each layer of event processing is performed layer by level
function, to the outermost HTML end.
IE8 Event Cycle: 2 stages: no capture

3. Event object:
Automatically created when an event occurs, encapsulates event information
For example: KeyCode
screenx/y
Get the Event object:
html:onclick= "Fun (event)"
When actually called: event automatically obtains the current event object
Fun (e) {
What you get in E is the event object.
}

Js:elem.onxxxx=fun;
Fun () {
Dom Standard: Automatically create an event object, passed in with the first parameter by default!
Ie8:window the global event property,
The event object is also created automatically when an incident occurs.
But it will be saved in window.event.
}
The Event object contains:
1. Target element object: var src=e.srcelement| | E.target
2. * * * Cancel/Use bubbling:
Cancellation: Dom standard: E.stoppropagation ()
Ie8:e.cancelbubble=true;
Typically used at the end of the current event handler execution
Optimization: If the same event handler is defined in multiple child elements
In fact, you just need to define it once on a common parent element!
3. * Cancel Event:
if (E.preventdefault) {
E.preventdefault (); --dom
}else{
E.returnvalue=false; --ie8
}
When to cancel: for example: Before the form is submitted, if the validation does not pass,
Auto-commit after cancellation

Event coordinates: 3 Coordinate systems
1. Relative to the display:
Maximum value: screen.availheight/availwidth
Mouse Position: e.screenx/y
2. Relative to the document display area
Maximum value: window.innerheight/width
Mouse position: e.clientx/x; e.clienty/y
3. Relative to the upper-left corner of the parent element
Maximum: The width and height of the parent element
Mouse Position: e.offsetx/y

Page scrolling

We recommend using JS to bind events

Event Coordinates:
The event object records the mouse position when an event occurs:
Relative to browser display coordinates location: clientx|x clienty|y
Position relative to the upper-left coordinate of the page: PageX PAGEY,IE8 not supported
The above two groups are equal when not scrolling.
Position relative to screen coordinates: ScreenX ScreenY
Coordinate position relative to the upper-left corner of the target element: OffsetX OffsetY

Dom&bom notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.