BOM and Dom

Source: Internet
Author: User
Tags list of attributes tag name

Foreplay

So far, we've learned some simple syntax for JavaScript. But these simple grammars do not have any interaction with the browser.

That is, we are not able to make some interactions with the pages we often see, and we need to continue to learn about BOM and Dom.

JavaScript is divided into Ecmascript,dom,bom.

The BOM (Browser object model) refers to the browser's objects models, which make JavaScript capable of "talking" to the browser.

The DOM (Document Object model) refers to all the elements of an HTML document that can be accessed by using it.

The Window object is one of the top-level objects of the client-side JavaScript, and since the Window object is a common ancestor of most other objects, the Window object's reference can be omitted when invoking the methods and properties of the Window object. For example: Window.document.write () can be simply written as: document.write ().

Window object

Window objects are supported by all browsers. It represents a browser window.

* If the document contains a frame (frame or iframe tag), the browser creates a Window object for the HTML document and creates an additional window object for each frame.

* There is no public standard applied to the Window object, but this object is supported by all browsers.

All JavaScript global objects, functions, and variables automatically become members of the Window object.

A global variable is a property of a Window object. A global function is a method of a Window object.

The next HTML DOM document is also one of the properties of the Window object.

Some of the commonly used window methods:

    • Window.innerheight-Interior height of the browser window
    • Window.innerwidth-Interior width of the browser window
    • window.open ()-Open a new window
    • Window.close ()-Close the current window
Child object of Window Navigator object (learn about it)

A browser object that can be used to determine the browser the user is using, including information about the browser.

Navigator.appname//Web browser full name navigator.appversion//web browser vendor and version of the detailed string navigator.useragent// Client most information navigator.platform//The operating system where the browser is running
Screen object (learn about it)

Screen objects, not commonly used.

Some properties:

    • Screen.availwidth-Available screen widths
    • Screen.availheight-The available screen height
History object (Learn it)

The Window.history object contains the history of the browser.

Browsing history objects, including the user's browsing history of the current page, but we can not see the specific address, it is simple to forward or backward a page.

History.forward ()//  forward one page history.back ()  //back one page
Location Object

The Window.location object is used to obtain the address (URL) of the current page and redirect the browser to a new page.

Common Properties and methods:

Location.href  Get urllocation.href= "URL"//Jump to the specified page location.reload () reload page
Pop-up box

You can create three message boxes in JavaScript: A warning box, a confirmation box, and a prompt box.

Warning Box

Warning boxes are often used to ensure that users can get some information.

When the warning box appears, the user needs to click the OK button to continue the operation.

Grammar:

Alert ("Did you see it?") ");

Confirmation box (learn about it)

The confirmation box is used to enable users to verify or accept certain information.

When the confirmation box appears, the user needs to click the OK or Cancel button to continue the operation.

If the user clicks Confirm, then the return value is true. If the user clicks Cancel, the return value is false.

Grammar:

Confirm ("Are you sure?" ")

Prompt box (learn to do)

The prompt box is often used to prompt the user to enter a value before entering the page.

When the prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue the manipulation.

If the user clicks Confirm, then the return value is the value entered. If the user clicks Cancel, the return value is null.

Grammar:

Prompt ("Please enter below", "your Answer")
Timing related

By using JavaScript, we can execute code after a certain interval of time, rather than executing it immediately after the function is called. We call this a timing event.

SetTimeout ()

Grammar:

var t=settimeout ("JS statement", MS)

The SetTimeout () method returns a value. In the above statement, the value is stored in a variable named T. If you want to cancel the setTimeout (), you can use the variable name to specify it.

The first argument to SetTimeout () is a string containing a JavaScript statement. This statement may be such as "alert (' 5 seconds! ')" or a call to a function, such as alertmsg () ".

The second parameter indicates how many milliseconds from the current to execute the first parameter (1000 milliseconds equals one second).

Cleartimeout ()

Grammar:

Cleartimeout (settimeout_variable)

As an example :

Executes the corresponding function once after the specified time var timer = setTimeout (function () {alert (123);}, 3000)//Cancel SetTimeout Settings cleartimeout (timer);

SetInterval ()

The SetInterval () method invokes a function or evaluates an expression according to the specified period (in milliseconds).

The SetInterval () method keeps calling functions until Clearinterval () is called or the window is closed. The ID value returned by SetInterval () can be used as a parameter to the Clearinterval () method.

Grammar:

SetInterval ("JS statement", time interval)

return value

A value that can be passed to Window.clearinterval () to suppress periodic execution of code.

Clearinterval ()

The Clearinterval () method cancels the timeout set by SetInterval ().

The parameter of the Clearinterval () method must be the ID value returned by SetInterval ().

Grammar:

Clearinterval (ID value returned by setinterval)

As an example:

Every once in a while the corresponding function is executed var timer = setinterval (function () {console.log (123);}, 3000)//Cancel SetInterval Settings clearinterval (timer) ;

A slightly larger example:

<! DOCTYPE html>
Timer ExampleDom

The DOM (document Object Model) is a set of methods for abstracting and conceptualizing the contents of a document.

When a Web page is loaded, the browser creates a Document object model for the page.

The HTML DOM model is constructed as a tree of objects.

HTML DOM Tree

The DOM standard specifies that each component in an HTML document is a node:

    • Document node (object): Represents the entire document
    • Elements node (element Object): Represents an Element (label)
    • Text node (text object): Represents the text in an element (label)
    • Attribute node (Attribute object): Represents an attribute, an element (label) has an attribute
    • Note is a comment node (Comment object)

JavaScript can create dynamic HTML through the DOM:

    • JavaScript can change all HTML elements in a page
    • JavaScript can change all HTML attributes in a page
    • JavaScript can change all CSS styles in a page
    • JavaScript can react to all the events in the page
Find tags to find directly
document.getElementById           gets a label based on the ID document.getelementsbyclassname   Get document.getElementsByTagName based on the class attribute     get Tag collection based on tag name

Attention:

The JS code that involves DOM manipulation should be placed in the document's location.

Indirect lookup
Parentelement            Parent node Tag element children                 All child tags firstelementchild        first child label element Lastelementchild         Last child tag element nextelementsibling       Next sibling tag element previouselementsibling   Previous sibling tag element
Node Operations Create nodes

Grammar:

CreateElement (sign)

Example:

var Divele = document.createelement ("div");
Adding nodes

Grammar:

Append a child node (as the last child node)

Somenode.appendchild (NewNode);

Put the added node in front of a node.

Somenode.insertbefore (NewNode, a node);

Example:

var imgele=document.createelement ("img"); Imgele.setattribute ("src", "http://image11.m1905.cn/uploadfile/s2010/ 0205/20100205083613178.jpg "), var D1ele = document.getElementById (" d1 ");d 1ele.appendchild (Imgele);
To delete a node:

Grammar:

Gets the element to delete, called by the parent element to delete.

RemoveChild (the node to be deleted)

Replace node:

Grammar:

Somenode.replacechild (NewNode, a node);

Attribute node

Gets the value of the text node:

var Divele = document.getElementById ("d1") DivEle.innerTextdivEle.innerHTML

Set the value of the text node:

var Divele = document.getElementById ("d1") divele.innertext= "1" divele.innerhtml= "<p>2</p>"

Attribute operation

var Divele = document.getElementById ("d1");d Ivele.setattribute ("Age", "+") Divele.getattribute ("Age") Divele.removeattribute ("Age")//The property can also be directly. property name to get and set imgele.srcimgele.src= "..."
Get Value action

Grammar:

Elementnode.value

Applies to the following labels:

    • . Input
    • . Select
    • . TextArea
var Iele = document.getElementById ("I1"); Console.log (iele.value); var Sele = document.getElementById ("S1"); Console.log (Sele.value); var tEle = document.getElementById ("T1"); Console.log (Tele.value);
Operation of Class
ClassName  get all style class names (strings)
Classlist.remove (CLS) Delete the specified class Classlist.add (CLS) Add Class
Classlist.contains (CLS) existence returns True, otherwise false
Classlist.toggle (CLS) exists on delete, otherwise added
Specifying CSS Actions
Obj.style.backgroundcolor= "Red"

JS Operation CSS Properties of the law:

1. For CSS properties that do not have a horizontal line, use the style directly. The property name. Such as:

Obj.style.marginobj.style.widthobj.style.leftobj.style.position

2. For CSS attributes with a horizontal line, change the first letter in the back of the middle line to uppercase. Such as:

Obj.style.marginTopobj.style.borderLeftWidthobj.style.zIndexobj.style.fontFamily
Event

One of the new features of HTML 4.0 is the ability to enable HTML events to trigger actions in the browser, such as starting a piece of JavaScript when the user clicks on an HTML element. The following is a list of attributes that can be inserted into an HTML tag to define an event action.

Common events
OnClick an        event handle that is invoked when a user taps an object. OnDblClick an     event handle that is called when the user double-clicks an object. The onfocus        element gets the focus.               //Exercise: The input box onblur         element loses focus.               scenario: For form validation, when a user leaves an input box, the Representative has already entered it and we can verify it.       the contents of the onchange domain are changed.             scenario: Typically used for form elements that are triggered when the element content is changed. (select linkage) onkeydown      a keyboard key is pressed.          Application Scenario: When the user presses the ENTER key in the last input box, the form submits. onkeypress     a keyboard key is pressed and released. onkeyup        a keyboard key is released. OnLoad         a page or an image to finish loading. onmousedown    the mouse button is pressed. OnMouseMove    Mouse is moved. onmouseout     the mouse to move away from an element. onmouseover    mouse moves over an element. Onselect      occurs when the text in the text box is selected. OnSubmit      The Confirm button is clicked, the object used is the form.
Binding method:

Way One:

<div id= "D1" onclick= "ChangeColor (this);" > Dot me </div><script>  function ChangeColor (ths) {    ths.style.backgroundcolor= "green";  } </script>

Attention:

This is an argument that represents the current element that triggered the event.

The ths in the function definition process is a formal parameter.

Way two:

<div id= "D2" > Point I </div><script>  var divEle2 = document.getElementById ("D2");  Divele2.onclick=function () {    this.innertext= "hehe";  } </script>

Examples of events:

<! DOCTYPE html>
Search Box Example
<! DOCTYPE html>

BOM and Dom

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.