Window object of BOM

Source: Internet
Author: User
Tags time in milliseconds

Dual role

The core object of the BOM is window, which represents an instance of the browser. In the browser, the Window object has a dual role, which is both an interface for accessing the browser window through JavaScript, and the global object specified by the ECMAScript. This means that any object, variable, and function defined in a Web page takes window as its global object.

Global scope

"1" variables and functions declared in the global scope become properties and methods of the Window object

var age =; function Sayage () {    Console.log (this. age);} Console.log (window.age); // sayage (); // window.sayage (); //  in

The "2" global variable cannot be deleted by the delete operator, and the properties defined directly on the Window object can be

[Note 1] in strict mode, only through window. xx to define the XX attribute, and through the delete window. XX Delete attribute will not error.
[Note 2] ie8-The browser encounters a statement that uses Delete to delete the Window property, or deletes a property of window, throws the wrong

"Use strict"var = "Red"; Delete window.age; // ie8-throw wrong, in strict mode also cast wrong Console.log (window.age); // Console.log (age); //  in
 use strict var  age = 29;window.color  = "Red" ;  delete  age; //   Console.log (window.age) is not allowed to invoke delete on an expression in strict mode; // 29  console.log (age); // 29  
 use strict var  age = 29;window.color  = "Red" ;  delete  color; // ie8-error, in strict mode, do not allow to call Delete to an expression  console.log (Window.color); // undefined  console.log (color); // is not defined  
"Use strict"var = "Red"; Delete Window.color; // ie8-cast the wrong Console.log (Window.color); // undefinedconsole.log (color); // is not defined

The "3" attempt to access an undeclared variable throws an error, but by querying the Window object, you can know if a variable that might not be declared exists

// throws an error because oldvalue is undefined var newvalue = oldValue; // does not throw an error, because this is a property query var newvalue = Window.oldvalue;

Window position

"1" Get

IE, Safari, Opera, chrome all support Screenleft and Sreentop
Firefox supports Screenx and Screeny

The compatible wording is as follows:

var leftpos = (typeof Window.screenleft = = "Number")? Window.screenLeft:window.screenX; var toppos = (typeof Window.screentop = = "Number")? Window.screentop:window.screeny;console.log (leftpos,toppos);     //  // due to different implementations of the browsers, exact coordinate values cannot be obtained under cross-browser conditions

"2" mobile

Use the MoveTo () and Moveby () methods to move the window precisely to a new location.
[level of support] only IE and safari support, and the implementation of different effects
[A]moveto () receives two parameters, which are the x and Y coordinate values of the new position, respectively

// Move the window to the upper-left corner of the screen function () {    Window.moveto (0,0);}

[B]moveby () receives two parameters, moving the number of pixels in both horizontal and vertical directions, respectively

// move the window 100 pixels down function () {    Window.moveby (0,100);}    

Window size

"1" Get

Innerheight and Innerwidth (the size of the Page view area in the window (minus the border width)) (ie9+)
Innerheight = Document.documentElement.clientHeight
Innerwidth = Document.documentElement.clientWidth
"Outerheight and Outerwidth" (browser window itself size) (ie9+)
"DOM:document.documentElement.clientWidth and Document.documentElement.clientHeight" (page viewport information) (fully compatible)
Page size compatible notation:

var pagewidth = document.documentElement.clientWidth; var pageheight = document.documentElement.clientHeight;    

"2" Adjustment

"Resizeto () and Resizeby ()" (only IE and safari support)

    [A]resizeto () receives two parameters: new width and new height of browser window

function () {    // adjust the browser window to 100,100    Window.resizeto (100,100);}

[B]resizeby () receives two parameters: the difference between the width and height of the browser's new window and the original window

function () {    // Increase the width of the browser windowby    Window.resizeby (100,0)    ;}

Open window

Use the window.open () method to navigate to a specific URL, or to open a new browser window. This method receives 4 parameters: the URL to be loaded, the window target, an attribute string, and a Boolean value that indicates whether the new page supersedes the currently loaded page in the browser history.

"1" Usually only passes the first parameter, and the last parameter is used only when a new window is not opened

function () {    // open baidu.com window.open ("http://baidu.com") in a new window    }

  

"2" passes the second argument, which can already have the name of a window or frame, or it can be _self, _parent, _top, _blank

function () {    // open baidu.com window.open in the current window    ("http://baidu.com", ' _self')} 
<! DOCTYPE html>function() {    // open qq.com in frame with name frame    window.open ("http://qq.com", ' Frame1 ')}</script>

[note] If the name of the second argument does not exist, it is equivalent to setting _blank, which opens a new window

function () {    // open qq.com window.open ("http://qq.com", ' abc ') in the frame with the nameframe     }

The third parameter of "3" is a comma-delimited set string that indicates which attributes are displayed in a new window

function () {    // opens a new window with a height of 500, a width of 500, an ordinate of 0, a horizontal axis of 200 QQ Web page    window.open ("http://qq.com", " _blank "," height=500,width=500,top=0,left=200 ")}    

"Scenario" can manipulate newly opened windows with objects returned by window.open ()

    //Click in the parent window to control the opening and closing of child windowsDocument.onclick =function(){    if(!window.obj1) {obj1= window.open ("http://baidu.com", "_blank", "height=400,width=400,top=10,left=10"); }Else{        //the newly created Window object has a opener property that holds the original window object that opened it. Console.log (Obj1.opener = =window)//close the newly opened windowObj1.close (); //Delete Obj1 Property        Deletewindow.obj1; }}  

[Security restrictions] if the window.open () statement is executed directly by the parent window code rather than by a click or other indirect action, the resulting child window will be masked by the pop-up blocker of most browsers.

var obj1 = window.open ("http://baidu.com", "_blank", "height=400,width=400,top=10,left=10"); if NULL {    alert (' popup is blocked ')}

[Detects if pop-up windows are blocked]

var false ; Try {    var obj1 = window.open ("http://baidu.com");     if NULL ) {        true;    }} CATHC (ex) {    true;} if (blocked) {    alert ("The popup was blocked");}

Timer

JavaScript is a single-threaded language, but it allows you to debug code at specific times by setting a time-out value and interval values. The former executes the code after the specified time, while the latter executes the code once every specified time.

"1" Timeout call (SetTimeout ())

Accepts two parameters: the code to execute and the time in milliseconds. Where the first argument can be a string, or it can be a function

// 1s popup 1setTimeout ("alert (1)", + +)//[note] It is not recommended to pass strings because passing strings can result in performance loss //  1s pops up 1setTimeout (function() {    alert (1);},1000);

After calling SetTimeout (), the method returns a numeric ID that represents the timeout call. This timeout call ID is a unique identifier for the plan execution code that can be called by calling the Cleattimeout () method to cancel the timeout call.

/Set Timeout call var timeoutid = setTimeout (function() {    alert (1);},+); // Cancel Timeout Call cleartimeout (timeoutid); // [note] You can completely cancel the timeout call    as long as you call Cleartimeout () before the specified time has elapsed

"2" Intermittent call (SetInterval ())

Executes the outer code repeatedly at the specified interval until the intermittent call is canceled or the page is unloaded. Accepts two parameters: the code to execute and the time in milliseconds. The first parameter can be either a string or a function.

// 1 setinterval after 1s per interval("alert (1)", + +)//[note] It is not recommended to pass a string because passing a string can result in a performance loss // 1 setinterval (function() {    alert (1);},1000) after each interval of 1s;

The call to the SetInterval () method can also set an intermittent invocation ID, which is a unique identifier for the plan execution code that can be called by the Cleatinterval () method to cancel the intermittent call.

var num = 0; var max = ten; var NULL ; function Incrementnumber () {    num++    ; // cancels subsequent calls that are not executed if the number of executions reaches the value set by Max    if (num = = max) {        clearinterval (intervalid);        Alert (' 1 ');     = SetInterval (incrementnumber,500);    

In this example, the variable num increments every 500ms, and the previously set intermittent call is canceled when it is incremented to the maximum value. This pattern can also be implemented using a timeout call.

varnum = 0;varmax = 10;functionincrementnumber () {num++; //set another timeout call if the number of executions reaches the value set by Max    if(Num <max) {setTimeout (Incrementnumber,500); }Else{alert ("1"); }}settimeout (Incrementnumber,500); /*As you can see, there is no need to trace the timeout call ID when using a time-out call, because after each code execution, the call stops itself if another timeout call is no longer set. */

In a development environment, a real intermittent call is seldom used because the latter intermittent call may be started before the end of the previous intermittent call. It's best not to use intermittent calls, which are the best mode for simulating intermittent calls using a timeout call.

System dialog box

The browser uses the alert (), confirm (), prompt () method to invoke the System dialog box to display information to the user. The dialog boxes opened by these three methods are both synchronous and modal, which means that the code stops executing when the dialogs are displayed, and the code resumes execution when the dialogs are closed.

"1" alert (): Receives a string and displays it to the user

Alert (1);

  

"2" confirm (): Receives a string and displays it to the user. Boolean value returned: True means that clicking Ok,false means clicking Cancel or the Close button in the upper-right corner

if (Confirm ("Is you sure?") ) {    alert ("I ' m so glad you ' re sure!") );} Else {    alert ("I ' m sorry to hear your ' re not sure.") )}    

  

"3" prompt (): Receives two parameters, the text hint to be displayed to the user and the default value of the text input field (can be an empty string). Returns the value of the text input field if the user clicked the OK button, or returns null if the user clicked Cancel or the Close button in the upper-right corner.

var result = Prompt ("What is your name?", "Mike"); if NULL {    alert ("Welcome," +result);    } Console.log (Result)

Print

The Print dialog box is displayed asynchronously, allowing control to be returned to the script immediately.

// Show Print dialog box window.print ();

Window object of BOM

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.