JavaScript Browser Object Model BOM Use Introduction _ Basics

Source: Internet
Author: User
Tags object model setinterval blank page

The BOM, also known as the browser object model, provides a number of objects for accessing the browser's functionality, which is irrelevant to any web content;
BOM lacks the specification, each browser provider according to own idea expands it, then the browser common object becomes the fact standard;

A Window object

The core object of the BOM is window, which represents an instance of the browser;
The Window object is at the top level of the JavaScript structure;
For each open window, the Windows object is automatically defined for the system;
The Window object acts as the role of the global object in the ECMAScript, so all variables/functions declared in the global scope become properties and methods of the Window object;
PS: Attempting to access an undeclared variable throws an error, but by querying the Window object, you can know if an object that may not be declared exists;
  var newvalue = OldValue;        =>referenceerror:oldvalue is not defined;
  var newvalue = Window.oldvalue;     =>undefined;

Properties and methods of 1.window objects
the Window object has a series of properties that are themselves objects;

(1). Property
Property meaning
Closed is true when the window closes, and the default state information displayed in the status bar at the bottom of the
defaultstatus window;
Document The Document object currently displayed in the window; An array of frame objects in the
frames window; The
history saves a URL that has been recently loaded by the window; The number of frames in the
length window; The
location the URL in the current window; The
Name window name;
Offscreenbuffering is used to draw new window content and to copy existing content after completion, to control screen updates;
Opener opens the window of the current window;
Parent points to a window containing another window (used by the frame);
Screen displays information about the screens, such as height/width (in pixels;)
Self indicates the current window;
Status describes temporary information for the status bar caused by user interaction;
Top contains the topmost window for a particular window (used by the frame);
Windows indicates the current window, equivalent to self;

(2). method
alert (text) Creates a warning dialog box that displays a message;
Blur () removes the focus from the window;
Clearinterval (interval) clears the timer interval previously set;
Cleartimeout (timer) clears the timeout set before;
Close () closes the window;
Confirm () Create a dialog box that needs to be validated;
Focus () moves the focal point to the window;
Open (Url,name,[options]) opens a new window and returns the new Windows object;
Prompt (Text,defaultinput) creates a dialog box that requires the user to enter information;
Scroll (x,y) is scrolled to a pixel position in the window;
SetInterval (expression,milliseconds) computes an expression at a specified time interval;
SetInterval (Function,millisenconds,[arguments]) calls a function after a specified time interval;
settimeout (expression,milliseconds) computes an expression after the timer is exceeded;
Stetimeout (Function,milliseconds,[arguments]) calls a function after the timer is exceeded;
Print () to pull out the printing dialog box;
Find () Pull up the Lookup dialog box;
Properties and methods under Windows, you can use the window. property, Window. method () or a direct property, method () call;
Window.alert (text) =alert (text);

2. System dialog box
the browser invokes the System dialog box with the alert ()/confirm () and prompt () method to display the information to the user;
The System dialog box is not related to the Web page displayed in the browser, nor does it contain HTML;
Their appearance is determined by the operating system and/or browser settings, not by CSS;
These open dialog boxes are synchronized and modal, that is, the code stops when the dialog is displayed, and the code resumes after the dialog box is turned off;

Pop-up warning
  alert (' warning ');

Confirm and Cancel
  if (Confirm (' Please confirm or Cancel ') {          //confirm () itself has a return value;
    Alert (' You have chosen to determine ');           Press OK to return a true value;
  } else{
    alert (' You have chosen to cancel ');           Press Cancel to return false value;
  }

Input prompt box
  var num = prompt (' Enter a number ', 0);     The first argument is a text hint, the second argument is the input box mode fill value, and returns the value
  in the input box; alert (num);                 Assigns the value returned by the prompt () method to the variable num, and pops up;

Call Print and Find dialog box print
  ();                   Print pop-up browser print window;
  Find ();                   =>boolean; page has matching lookup content returns true; relative to Ctrl+f;

Status bar
  defaultstatus = ' status bar default text ';       The initial default value of the status bar at the bottom of the browser;
  Status = ' state bar text ';            Browser bottom status bar setting value;

3. New Window (open ())

You can navigate to a specific URL by using the window.open () method, or you can open a new browser window;
It receives four parameters:
(1). URL to load;
(2). window's name or window target;
(3). a specific string;
(4). A Boolean value that indicates whether the new page replaces the currently loaded page in the browser record;
Open (' www.baidu.com '); Chrome-search://local-ntp/www.baidu.com, open failed, need to add http://;
Open (' http://www.baidu.com '); New page and jump to Baidu;
Open (' http://www.baidu.com ', ' search engine '); New page Open Baidu page and name window, and will not automatically jump, and call again just refresh that page;
Open (' http://www.baidu.com ', ' _parent '); Open Baidu on this page; ' _blank ' is to specify a new page to open;
Third string parameter
Set Value Description
Width of the new window, not less than 100px;
Height value of the new window, not less than 100px;
Top value the y-coordinate of the new window, which cannot be negative;
Left value the x-coordinate of the new window, which cannot be negative;
Whether the location Boolean displays the address bar in the browser window; different browser defaults;
Whether the MenuBar Boolean displays the menu bar in the browser window and defaults to No;
Whether the resizable Boolean changes size by dragging the browser window border;
ScrollBars Boolean If the page contents are not displayed, scroll bars are displayed;
Whether the status Boolean displays the State bar in the browser window, default no;
Whether the toolbar Boolean displays the toolbar in the browser, default no;
Fullscreen boolean browser window is maximized; IE support only;
Open (' http://www.baidu.com ', ' Baidu ', ' Width=400,height=400,top=200,left=200,toolbar=yes ');

Open () itself returns the Window object
var box = open (); A Window object was returned, and a new blank page was opened;
Box.alert ("); Then specify a new page window to open the object returned by the open ().

Word Window Action Parent window
Document.onclick = function () {//Click Docuement object in New window;
Opener.document.write (' Sub window Let me output! '); /At this time the parent window that produces it will generate text content;
}

4. The position and size of the window

(1). The position of the window
//used to determine and modify the position of the Windows Object (browser window) relative to the screen:/
/Ie+safari+opera+chrome all provide Screenleft and Screentop properties,
// Firefox provides Screenx and Screey attributes;
They represent the position of the window teller to the left and top of the screen respectively;
  
Determines the position of the window =>ie
  alert (screenleft);              The distance from the left side of the browser to the screen;
Determines the position of the window =>firefox
  alert (ScreenX);                The distance from the left side of the browser to the screen;

Cross-browser method
  var leftx = (typeof screenleft = ' number ')? Screenleft:screenx;
  Determine whether the detection of screenleft is a value, if the use of Screenleft value, otherwise use Screenx value;

(2). The size of the window//check the size of the browser window itself and the border: Outerwidth and Outerheight;
  alert (outerwidth);
alert (outerheight);
  Detect page Size properties: Innerwidth and Innerheight;
  alert (innerwidth);
alert (innerheight); Ps:ie does not provide properties for the current browser window size;

There are methods in the DOM that provide correlation;
In IE and other browsers, provides: Document.documentElement.clientWidth and document.documentElement.clientHeight; To save the information of the page window;
PS: In IE6, the above attributes are valid in standard mode, and if it is a weird mode, it must pass through Document.body.clientWidth and document.body.clientHeight;
  If it is Firefox and other browsers, direct use of innerwidth and innerheight;        var width = window.innerwidth;
  Add window here, because IE will not work;
  var height = window.innerheight; if (typeof width!= ' number ') {//IE6 browser if (Document.compatmode = = ' Css1compat ') {//judgment is IE6 standard mode; use Documenteleme
      nt
      width = document.documentElement.clientWidth;
    Height = document.documentElement.clientHeight;
      }else{//Otherwise is IE6 non-standard mode;
      width = document.body.clientWidth;
    Height = document.body.clientHeight;
  }//PS: The above methods can be used in different browsers to obtain the size of the visual part of the browser window; Document.compatmOde can determine whether the page is in standard mode; 
Adjust the browser location;
  MoveTo (0,0);                 Move to (0,0) coordinates; IE effective;
  Moveby (10,10);                Moving down and to the right respectively 10px;ie effective;

Resize Browser size
  resizeto (200,200);              Adjust the size;
  Resizeby (200,200);              Expand the shrinkage size;

5. Intermittent calls and timeout calls
1//JavaScript is a single-threaded language, but it allows you to schedule code to execute at a specific time by setting the timeout value and the intermittent time values;
2//Timeout value: Executes the code after the specified time;
3//Interval value: Executes the code once at a specified time;

Timeout invokes the settimeout () method that uses the Window object;
It takes two parameters: the code to execute and the number of milliseconds;
  settimeout (function () {            //direct use of functions passed in method, scalability, performance more;
    Alert (' Warning! ');
  },1000);
After calling SetTimeout (), the method returns a numeric ID indicating the timeout call;
The ID of the timeout call is the unique identifier of the planned execution code, which can be used to cancel the timeout call;
To cancel a time-out call plan that has not yet been executed, you can call the Cleartimeout () method and pass the appropriate timeout call ID as a parameter to it;
  var box = settimeout (function () {       //The ID of the timeout call is assigned to the variable box;
    Alert (' timeout call ');
  },1000;
  cleartimeout (box);              Passing the ID into the cancel call method;
//intermittently invokes the SetInterval () method that uses the Window object;//It repeats the code at a specified interval until the intermittent call is canceled or the page is unloaded;
  It receives the same parameters as settimeout ();
  var pox = setinterval (function () {alert (' interval call ');
  },1000);              Clearinterval (POX);

Cancel intermittent calls;
  Use SetInterval () to set a timer of 5 seconds;                 var num = 0;
  Set start seconds;                 var max = 5;
  set termination seconds;                  SetInterval (function () {num++;
    Increment num;         if (num = max) {clearinterval (this);
      Cancel Interval call, this represents the method itself; the ID of the interval call;
    Alert (' 5 seconds Rear window '); 
}},1000); 
Generally using time-out to simulate interval invocation is a best model;
Because the use of interval calls requires the cancellation of IDs based on circumstances and may cause problems with synchronization; the latter intermittent call may start before the end of the previous intermittent call;
  var num = 0;
  var max = 5;
  function box () {
    num++;
    if (num = max) {
      alert (' 5 seconds Rear window ');
    } else{
      settimeout (box,1000);          Executes a timeout call again after 1 seconds;
  SetTimeout (box,1000);              execution timer; 
  PS: When using timeout calls, it is not necessary to trace the timeout call ID, because after each execution, if another timeout call is no longer set, the call will stop automatically;

Two Location objects

Location is one of the BOM objects that provides information about the documents loaded in the current window, and also provides navigation capabilities;
In fact, the location object is the property of the Window object and the Document object;
alert (location); Get the current URL

(1). Properties of the Location object
the URL content of the attribute description
Hash if the part exists, represents the anchor point part;
Host hostname: port number;
hostname host name;
href entire URL;
pathname path name;
Port port number;
Protocol Agreement part;
Search returns the query string ('? Gws_rd=ssl#safe=strict&q=ab ') of the URL, which begins with a question mark;
(2). Methods of Location objects
Assign () jumps to the specified page, equivalent to the href;
Reload () overloads the current URL;
Replace () replaces the current page with a new URL;

Location.hash = ' #1 '; Set the string after #, and jump;
Location.hostname = ' Jack '; Set host name;
Location.search = ' id=5 '; Set the string after;

In web development, we often need to get key-value pairs
for URLs of this type, such as? Id=5&search=ok. By location, we can write a function to get one by one;
  function Getargs () {
    //Create an array that holds the key-value pairs;
    var args = [];
    Remove the number;
    var qs = location.search.length>0?location.search.substring (1): ';
    Split fractions by & string;
    var items = qs.split (' & ');
    var item = NULL, name = NULL, value = NULL;
    Traversal for
    (var i = 0; i<items.length; i++) {
      item = items[i].split (' = ');
      Name = decodeURIComponent (item[0]);  Because the query string has been encoded by the browser;
      Value = decodeURIComponent (item[1]);//each query string parameter becomes the property of the args object;
      Storing the key value pairs in the array;
      Args[name] = value;
    }
    return args;
  }
  var args = Getargs ();
  Alert (args[' id '));              Gets the value corresponding to the ID in the URL;

Copy Code code as follows:

Location.assign (' http://www.baidu.com '); Jumps to the specified url;2
Location.reload (); The most efficient reload, it is possible to load from the cache;
Location.reload (TRUE); Force load, reload from server source; 5
Locatioin.replace (' http://www.baidu.com '); On this page to jump to Baidu page, and can avoid the history of the jump;

Three History objects

The history object is the property of the Window object that holds the record of the user on the Internet, from the moment the window is opened;

(1). Properties of the History object

The number of records in the length history object;
(2). Methods of History objects
Back () go to the browser history bar at present a URL, similar to backward;
Forward () go to the browser history entry next URL, similar to forward;
Go (NUM) browser forward or backward in the history object;

Copy Code code as follows:

function back () {
History.back ();
}
function forward () {
History.forward ();
}
function Go (num) {
History.go (num);
}
PS: Can be judged by history.length = = 0, whether there is a historical record;

Iv. Summary

The

  Browser object Model (BOM) is based on window objects, representing the browser window and the visible area of the page; The
  Window object is also the global object in ECMAScript, so all global variables and functions are its properties, and all native constructors and other functions exist under its namespace;
  (1). Using the Location object, you can programmatically access the browser's navigation system, and set the appropriate properties to modify the URL of the browser piecemeal or in a holistic manner;
  (2). Call the Replace () method to navigate to a new URL that replaces the page currently displayed in the browser's history;
  (3). Screen object: Holds information about the client display, which is typically used only for site analysis;
  (4). History object: A small gap in the history of the access browser allows developers to determine the number of historical records, or navigate backwards or forwards to any page in the history;

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.