The Window object in JavaScript is simple to learn

Source: Internet
Author: User
Tags event listener hash setinterval javascript settimeout

the 1.Window object is the primary access point for all client JavaScript features and APIs.

An important property in the Window object is document, which references the Document object.
A JavaScript program can traverse and manage documents through the document object and the element objects it contains.

JavaScript in 2.URL

Follow the URL followed by a javascript: protocol qualifier. The code inside is run as JavaScript code, separated by semicolons.
Such as:

<a href= "Javascript:alert (' ok! ')" ></a>

Because the <a> label usually scopes a hyperlink, it loads the new document. If you want to use and the URL does not overwrite the current document,
You can use the void operator to force a function call or assign an undefined value to an expression:
Such as:

<a href= "javascript:void window.open (' About:blank ');" ></a>

the implementation of 3.JavaScript is divided into two phases:

Phase one: Load the contents of the document and execute the code in the <sacript> element
Phase two: Document loading complete, and after script execution completes, enter this second phase.
This phase is asynchronous and is driven by events. In the event-driven phase, the Web browser invokes an event handler function.

4. If you want the program to correspond to an event, write a function called "event handler" or "Event listener" or "callback" ,

Then register the function so that he will call it when the event method occurs.
Most of the time in the browser, an object is passed to an event handler as a parameter, and the object's properties provide details of the event.
For example, the object that is passed to the Click event will have a property indicating which button of the mouse is clicked (in IE
, these event information is stored in the global event object instead of being passed to the handler function. )
The return value of an event handler is sometimes used to indicate whether the function has adequately handled the event, and to prevent the browser from performing various actions that it will do by default.

Some events are targeted at document elements, and they are often passed on the web to the document tree, a process called "bubbling."

If you want to register multiple event handlers for an event, you can use the AddEventListener () method to allow multiple listeners to be registered.
Such as:

Window.addeventlistener ("Load", function () {...},false);

This method is realized on the IE9. In IE8 and previous browsers, a similar method must be used, which is attachevent ()

Window.attachevent ("Load", function () {...});

the conditional annotation inside the 5.IE

In order to deal with the incompatibility of IE, it is necessary to encode ie in some way, which is one of the conditions introduced.
In my previous article there is a detailed description of:<!--[if IE 9]>....<!end if-->

6. Parse URL

The Location object is part of a Window object that can be accessed by the Window.location property



7. Browsing History

The window-exclusive history property refers to the history object of the Windows.
The history object is used to represent the browsing history of a window in the form of a list of documents and document states.

History.back ()//back
History.forward ()/forward
History.go (-2)//back two historical records

jquery has history plug-ins.

8. Browser and screen information

The Navigator property of the A:window object refers to the Navigator object that contains the browser manufacturer and version information.
Example:

<div id= "Example" ></div>

<script>

TXT = "<p>browser codename:" + Navigator.appcodename + "</p>";
txt+= "<p>browser Name:" + navigator.appname + "</p>";
txt+= "<p>browser Version:" + navigator.appversion + "</p>";
txt+= "<p>cookies Enabled:" + navigator.cookieenabled + "</p>";
txt+= "<p>platform:" + navigator.platform + "</p>";
txt+= "<p>user-agent Header:" + navigator.useragent + "</p>";
txt+= "<p>user-agent language:" + navigator.systemlanguage + "</p>";

document.getElementById ("Example"). Innerhtml=txt;

</script>

Warning: The information from the Navigator object is misleading and should not be used to detect browser versions because:

Navigator data can be changed by browser consumer
The browser could not report a new operating system later than the browser release


The screen property of the B:window object refers to the screen object.

9. dialog box

The Window object provides three ways to display a simple dialog box to the user
Alert ()
Comfirm ()
Prompt ()
These three methods will cause blocking.
There's a more complicated approach ShowModalDialog ()


JavaScript Window object

The Window:window object is the core of all objects in the BOM, and includes some window control functions in addition to the parent object of all objects in the BOM.

1, the Global Window object

Any global function or variable in JavaScript is a property of window.

<script type= "Text/javascript" >
var name= "Shake sacred Cattle";
document.write (window.name);
</script>


2, window and self object

The Self object is exactly the same as the Window object, and self is typically used to confirm that it is within the current form.

<script type= "Text/javascript" >           document.write (window == self); Must be equal, always equal document.write (window.  Top == window.self); Determines whether the current frame is the main frame </script> 

The


window, self, and window.self are equivalent. The main objects of

3, window's Child

window are mainly as follows:

    JavaScript Document Object
    JavaScript Frames Objects
    JavaScript history Objects
    JavaScript Location Objects
    JavaScript Navigator Objects
    JavaScript screen objects

4, window function index (valid only for IE)

Form control function:

    JavaScript moveby () Function: Move form x pixels horizontally from current position, move form y pixel vertically, X is negative, move form left, Y is negative, move form up.
    JavaScript moveTo () function: Moves the top-left corner of the form to the (x,y) point relative to the upper-left corner of the screen, and moves the form out of the viewable area of the screen when negative numbers are used as arguments.
    JavaScript Resizeby () function: Adjusts the width of w pixels relative to the current size of the form, and adjusts h pixels height. If the argument is negative, the form is narrowed, and the form is enlarged.
    JavaScript Resizeto () function: Adjusts the width of the form to w pixels and height to h pixels.


<body>     <input type= button " id=" BTN1 " value=" set the form fixed size first! " onclick=" Window.resizeto (500,500); "  />     <input type= "button"  id= "Btn2"  value= "and then reduce the 10 pixel! " onclick=" Window.resizeby ( -10,-10);  />     <input type= "button"  id= "Btn2"  value= "On! " onclick=" Window.moveby (0,-5);  />     <input type= "button"  id= "BTN2"  value= "! " onclick=" Window.moveby (0, 5);  />     <input type= "button"  id= "Btn2"  value= "Left!" " onclick=" Window.moveby ( -5, 0);  />     <input type= "button"  id= "btn2"  value= "right! " onclick=" Window.moveby (5, 0);  />     <input type= "button"  id= "Btn2"  value= "is 100 pixels to the left of the upper left corner, Top 200 pixel " onclick=" Window.moveto (100, 200);  />;/body> 



Form Scroll axis control function:

JavaScript Scrollto () function: If you have a scroll bar in a form, move the horizontal scroll bar to the position relative to the width of the form x pixels, and move the longitudinal scroll bar to the position of y pixel relative to the form's height.
JavaScript Scrollby () function: If you have a scroll bar, move the horizontal scroll bar to the position of x pixels relative to the current horizontal scroll bar (that is, move x pixels to the left), and move the longitudinal scroll bar to the position of y pixels relative to the current vertical scroll bar height (that is, move y pixels down).

Notice the difference, one is relative to the current window, and one is the position of the scroll bar quite now.

<div style= "height:150%; width:150%; Background-color: #ddd ">
<input type=" button "id=" BTN1 "value=" Move scroll bar! "Onclick=" Window.scrollto (100,100); "/>//equivalent to set absolute position
<input type=" button "id=" BTN1 "value=" Move scroll bar! "Onclick=" Window.scrollby (100,100); "/>//equals cumulative
</div>


Form Focus Control Function:

JavaScript focus () function: Get the form or space focused
JavaScript blur () function: causes a form or control to lose focus

<div>
<input type= "button" value= "gets Focus" onclick= "document.getElementById (' Testinput '). Focusing ()"/><  c1/> <input type= "button" value= "Loses focus" onclick= "document.getElementById (' Testinput '). blur ()"/> <input
Type= "Text" value= "text" id= "Testinput" onblur= "alert (' I have lost Focus ')"/>
</div>


New Form function:

JavaScript open () function: open (eject) a new form
JavaScript Close () function: Closing a form
JavaScript Opener Properties: You can communicate across forms by opener, but make sure that you are under the same domain name and that one form contains the opener of another form.

window.open (URL, name, features, replace);

Open function Parameter Description:

URL--the URL to load the form into;
Name--Creates a new form (also can be the value of the HTML target property, the target);
Features--a string representing the attributes of a form, separated by commas in each attribute of the string;
Replace--A Boolean value that indicates whether the newly loaded page replaces the currently loaded page, and this parameter is usually not specified.

An example of the Open method:

<a href= "2.html" target= "2" > Open Connection in New window </a>
<a href= "#" onclick= "window.open (' http://www.google.com ', ' 2 ');" > Open a new address on a connected page </a>

First open a page with a normal HTML link (target named Dreamdu), and then open another page using the Open function, the browser first looks for a form with a name of DREAMDU, and if so, loads the open address in the form.

The Set Open

window.open (' page.html ', ' newwindow ', ' height=100, width=400, top=0,left=0, Toolbar=no, Menubar=no, Scrollbars=no, Resizable=no,location=no, Status=no ')

Window method:

Method One: <body onload= "Openwin ()" > Browser pop-up window when reading the page;
Method Two: <body onunload= "Openwin ()" > Browser out of the page pop-up window;

Parameter name type Description
Height Number Set the height of the form, not less than 100
Left Number Description creates the left coordinate of the form, not a negative value
Location Boolean Whether the form displays the Address bar and the default value is no
Resizable Boolean Whether the form allows resizing by dragging the edge, the default value is no
Scrollable Boolean If the interior of the form is outside the window's viewable range, drag is allowed, and the default value is no
Toolbar Boolean Whether the form displays a toolbar, and the default value is no
Top Number Shows the top coordinates of the form being created and cannot be negative
Status Boolean Does the form display a status bar with the default value no
Width Number Create the width of the form, not less than 100


Each attribute in an attribute string is separated by commas, with no spaces allowed between each attribute.

When a new form is created, the Window.Open function returns the Window object for the new form, which allows you to control the form (move, resize, close).

Close function:

<input type= Button "value=" closes the form already open! "Onclick=" Window.close (); "/>

Self.close (), with the settimeout () can be implemented, open the window to the effect of timed shutdown.

dialog box functions:

JavaScript alert () Function: Pop-up message dialog (there is an OK button in the dialog box)
JavaScript confirm () Function: Pop-up message dialog box (contains an OK button and Cancel button in the dialog box)
JavaScript prompt () Function: Pop-up message dialog box (contains an OK button, Cancel button, and a text input box in the dialog box)

alert ();

Don't say.

Confirm (str);

The Confirm () Message dialog box is exclusive, which means that no other action can be performed until the user clicks the button on the dialog box.

if (confirm) (OK jump big?) ")"
{
alert ("Resolute hop Big");
}
else
{
alert ("Wretched dozen money");
}


The display is as follows:


Prompt (str1, str2);

function has two parameters

STR1-text that you want to appear in the message dialog box, cannot be modified
STR2--The contents of the text box, you can modify

var sresult=prompt ("Please enter your name below", "Shake Sacred Cow");
if (sresult!=null)
{
alert (Sresult + "has exceeded the Kill of God");
}
else
{
alert ("John Doe is beyond the Kill of God");
}


The display is as follows:


Time wait and interval function:

JavaScript settimeout () function
JavaScript cleartimeout () function
JavaScript setinterval () function
JavaScript clearinterval () function

1, settimeout (), cleartimeout () call the function after the specified time

Grammar:

SetTimeout (Fun,time); Fun: function body or function name, time specified in milliseconds.
Cleartimeout (ID); Cancels the code that the specified settimeout function will execute

settimeout (function () {
document.write ("trigger every 3 seconds");     
}, 3000)//3 seconds after output
settimeout (FUN1, 5000);    Output function
fun1 () {
document.write ("The method of the functions name is triggered after 5 seconds") after 5 seconds;
}


2, SetInterval (), clearinterval (value) repeatedly calls the function after the event specified at interval

Grammar:

SetInterval (fun1,time) Fun: function body or function name, time specified in milliseconds. Returns a value that is used to count the number of functions, the first is 1, and the second is 2, which indicates the SetInterval function.
The value returned by the Clearinterval (value) value:setinterval () function to stop the repetition of setinterval ().

var i = 0;
var h = setinterval (function () {
document.write ("3 seconds Output <br/>");
i++;
if (I >= 3) {
clearinterval (h);
document.write ("Stop Output");
}
, 3000);


Note that JavaScript is single-threaded, so the timing function is actually implemented by inserting the execution queue.

As in the following code:

function fn () {
settimeout (function () {alert (' Can you I/I/I? ');},1000);
while (true) {}
}


alert (); will never execute because the thread has been consumed by the dead loop.

Window.location Child Objects

Resolves a URL object location

The properties of the Location object are: Href,protocal,host,hostname,port,pathname,search,hash

     document.write (location.href +  "<br/>");         // http://localhost:4889/javascripttest.html       
  document.write (location.protocol +  "<br/>");     // http:         document.write (location.host +  "<br/>");         // localhost:4889        
 document.write (location.hostname +  "<br/>");     // localhost         document.write (location.port +  "<br/>");         // 4889          document.write (location.pathname +  "<br/>");     // / Javascripttest.html    &Nbsp;    document.write (location.search +  "line <br/>");   //http:// Localhost:4889/javascripttest.html?id=1&name= John   If the path is this, the output   ?id=1&name=%e5%bc%a0%e4%b8 %89         document.write (Location.hash);                   //http: //localhost : 4889/javascripttest.html#kk= hello? id=1&name= John   If the path is this, the output    #kk = hello? id=1&name= John



Load New document

Location.reload () reload page

Location.replace () This window loads a new document

Location.assign ()   This window loads the new document

location = "http://www.baidu.com"//jump to the specified URL

location = "search.html"//Relative Path jumps

location = "#top"//jumps to the top of the page

Browsing history

History () object's back () and forward () are the same as the browser's "backward" and "forward" features 。  

History.go (-2); Back two history

Browser and screen information

navigator.appname web browser full name

navigator.appversion web browser manufacturer and version of the detailed string
navigator.useragent Client Most information

Navagator.platform the operating system where the browser is running

        document.write ( navigator.useragent +  "<br/>"); // mozilla/5.0  (windows nt 6.1)   applewebkit/537.11  (Khtml, like gecko)  chrome/23.0.1271.97 safari/537.11          document.write (navigator.appname +  "<br/>");    //netscape         document.write (navigator.appVersion +   "<br/>"); //5.0  (windows nt 6.1)  AppleWebKit/537.11  (khtml,  Like gecko)  chrome/23.0.1271.97 safari/537.11          document.write (Navigator.platform);              //win32 



The relationship of the window

parent = self Only the top-level window returns true

The parent and top properties allow the script to reference the ancestor of its form, which is typically created by the <iframe> element and can be used to get the top-level window.

5, Event Events Object

The two most useful actions: Block event bubbling. sometimes return false; This may work, however.

IE:
window.event.cancelBubble = true;//stop bubbling
window.event.returnValue = false;//The default behavior of blocking events
//firefox:
Event.preventdefault ()//Cancel the default behavior of the event
event.stoppropagation ();//prevent the propagation of events


Related Article

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.