Introduction to object model BOM in JavaScript browser _ basic knowledge

Source: Internet
Author: User
This article mainly introduces the use of the JavaScript browser object model BOM. For more information, see BOM, also known as the browser object model. It provides many objects for accessing the browser; these functions are irrelevant to any webpage content;
BOM lacks standards. every browser provider expands it according to their own ideas, so the common objects of browsers become the standards of facts;

A window object

// The core object of BOM is window, which indicates an instance of the browser; // The window object is at the top of the JavaScript structure; // for each opened window, the system automatically defines the window object for it; // The window object also plays the role of the Global object in ECMAScript, therefore, all variables/functions declared in the global scope will become the properties and methods of the window object; // PS: an error will be thrown when you try to access undeclared variables, but by querying the window object, you can know whether an object that may not be declared exists; var newValue = oldValue; // => ReferenceError: oldValue is not defined; var newValue = window. oldValue; // => undefined;

1. properties and methods of window objects
Window objects have a series of attributes, which are also objects;

(1). attributes
Attribute meaning
Closed is true when the window is closed;
Default status information displayed in the status bar at the bottom of the defaultStatus window;
The document object currently displayed in the document window;
Array of frame objects in the frames window;
History stores the URL recently loaded by the window;
Number of frames in the length window;
Location URL in the current window;
Name window name;
OffscreenBuffering is used to draw new window content and copy existing content to control screen update;
Opener opens the current window;
Parent points to a window that contains another window (used by the framework );
Screen displays screen information, such as height/width (in pixels ;)
Self indicates the current window;
Status describes the temporary information of the status bar caused by user interaction;
Top the top-level window that contains a specific window (used by the framework );
Window indicates the current window, which is 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 previously set timer interval;
ClearTimeOut (timer) clears the previously set timeout;
Close () close the window;
Confirm () creates a dialog box for confirmation;
Focus () moves the focus to the window;
Open (url, name, [options]) opens a new window and returns a new window object;
Prompt (text, defaultInput) to create a dialog box that requires the user to enter information;
Scroll (x, y) scrolls to the position of a pixel in the window;
SetInterval (expression, milliseconds) calculates an expression at a specified interval;
SetInterval (function, millisenconds, [arguments]) calls a function after a specified interval;
SetTimeout (expression, milliseconds) calculates an expression when the timer is exceeded;
SteTimeout (function, milliseconds, [arguments]) calls a function when the timer is exceeded;
Print () call up the print dialog box;
Find () call up the search dialog box;
// The properties and methods in window can be called using window. properties, window. method (), or direct attributes and methods;
// Window. alert (text) = alert (text );

2. system dialog box
The browser uses the alert ()/confirm () and prompt () methods to call the system dialog box to display information to users;
The system dialog box is irrelevant to the webpage displayed in the browser and does not contain HTML;
Their appearance is determined by the operating system and (or) browser settings, rather than CSS;
The dialogs opened through these methods are both synchronous and modal. that is to say, the code stops running when these dialogs are displayed, and the code resumes execution after these dialogs are closed;

// Pop-up warning alert ('Shanghai'); // confirm and cancel if (confirm ('Please confirm or cancel') {// confirm () itself has a return value; alert ('you selected OK'); // return the true value according to OK;}) else {alert ('You selected cancel'); // Press cancel, return false;} // enter the prompt box var num = prompt ('Enter a number', 0); // The first parameter is a text prompt; the second parameter is the input box mode filling value, and returns the value in the input box; alert (num); // assigns the value returned by the prompt () method to the variable num; // call the print and search dialog box print (); // print; the browser print window is displayed; find (); // => boolean; return true if the page matches the search content; 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 = 'status bar text'; // set the value of the status bar at the bottom of the browser;

3. create a window (open ())

// You can use the window. open () method to navigate to a specific URL or open a new browser window;
// It receives four parameters:
// (1). URL to be loaded;
// (2). window name or window target;
// (3). a specific string;
// (4). indicates whether the new page replaces the boolean value of the currently loaded page in the browser record;
Open ('www .baidu.com '); // chrome-search: // local-ntp/www.baidu.com; opening failed; http: // needs to be added ://;
Open ('http: // www.baidu.com '); // Create a page and jump to Baidu;
Open ('http: // www.baidu.com ', 'search engine'); // open the Baidu page and name the window on the new page. the page does not jump automatically; and the page is refreshed when the call is made again;
Open ('http: // www.baidu.com ',' _ parent '); // open Baidu on this page;' _ blank 'indicates opening a new page;
// The third string parameter
Set value description
The width value indicates the width of the new window, which is not smaller than px;
The height value indicates the height of the new window, not smaller than 100px;
The Y coordinate of the new window of the top value, which cannot be a negative value;
The X coordinate of the new window of the left value, which cannot be a negative value;
Whether location boolean displays the address bar in the browser window; the default values of different browsers are different;
Whether the menubar boolean menu bar is displayed in the browser window. the default value is no;
Whether to change the size of resizable boolean by dragging the border of the browser window. the default value is no;
Scrollbars boolean whether to display the scroll bar if the page content cannot be displayed; no by default;
Status boolean indicates whether the status bar is displayed in the browser window. the default value is no;
Whether or not toolbar boolean displays the toolbar in the browser; no by default;
Whether the fullscreen boolean browser window is maximized; only IE supports;
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 is returned, opening a new blank page;
Box. alert (''); // then specify the new page that will be opened on the object returned by open;

// Word window operation parent window
Document. onclick = function () {// Click the docuement object in the new window;
Opener.doc ument. write ('subwindow let me output! '); // At this time, the text content is generated in the parent window that generates it;
}

4. window position and size

(1 ). the position of the window // used to determine and modify the position of the window object (browser window) relative to the screen: // IE + Safari + Opera + Chrome all provide the screenLeft and screenTop attributes, // Firefox provides the screenX and screeY attributes; // they indicate the position of the window relative to the left and top of the screen; // determine the position of the window => IE alert (screenLeft ); // The distance between the left side of the browser and the screen; // determine the position of the window => Firefox alert (screenX); // The distance between the left side of the browser and the screen; // Cross-browser method var leftX = (typeof screenLeft = 'number ')? ScreenLeft: screenX; // determines whether the screenLeft value is a numerical value. if so, use the screenLeft value; otherwise, use the screenX value;

(2 ). window size // Check the size of the browser window and its border: outerWidth and outerHeight; alert (outerWidth); alert (outerHeight); // check the page size attributes: innerWidth and innerHeight; alert (innerWidth); alert (innerHeight); // PS: IE does not provide the properties of the current browser window size; related methods are provided in the DOM; // in IE and other browsers, document.documentelement.clientwidthand document.doc umentElement are provided. clientHeight; to save the information of the page window; // PS: in IE6, the above attributes are valid in standard mode; if it is in weird mode, it must pass document. body. clientWidth and document. body. clientHeight ;/ /In Firefox or other browsers, use innerWidth and innerHeight; var width = window. innerWidth; // add a window here, because IE will be invalid; var height = window. innerHeight; if (typeof width! = 'Number') {// IE6 browser if (document. compatMode = 'css1compat') {// judge whether it is IE6 standard mode; use documentElement; width = document.doc umentElement. clientWidth; height = document.doc umentElement. clientHeight;} else {// otherwise, IE6 non-standard mode; use body; width = document. body. clientWidth; height = document. body. clientHeight; }}// PS: You can use different browsers to obtain the size of the visible part of your browser window. // document. compatMode determines whether the page is in standard mode;

// Adjust the browser location; moveTo (); // move to () coordinates; IE valid; moveBy (); // move 10 px down and to the right; IE valid; // Adjust the browser size resizeTo (200,200); // Adjust the browser size; resizeBy (200,200); // expand and contract the browser size;

5. intermittent call and timeout call
1 // JavaScript is a single-threaded language, but it allows code scheduling to be executed at a specific time by setting the timeout value and intermittent time value;
2 // timeout value: run the code after the specified time;
3 // interval value: code is executed every specified time;

// Timeout call the setTimeout () method of the window object; // it accepts two parameters: the code to be executed and the number of milliseconds; setTimeout (function () {// directly use the method passed in by the function, which provides better scalability and better performance. alert ('Warning! ');}, 1000); // after setTimeout () is called, this method returns a value ID, indicating that the call times out; // the ID of the time-out call is the unique identifier of the code to be executed. you can use this ID to cancel the time-out call. // to cancel the time-out call plan that has not been executed, you can call clearTimeout () method and pass the corresponding timeout call ID to it as a parameter; var box = setTimeout (function () {// assign the ID of the timeout call to the variable box; alert ('time-out call') ;}, 1000); clearTimeout (box); // pass the ID to cancel the call method;

// Call the setInterval () method of the window object intermittently; // it repeats the code at the specified interval until the call is canceled or the page is uninstalled; // It receives the same parameters as setTimeout (); var pox = setInterval (function () {alert ('Call interval ');}, 1000); clearInterval (pox ); // cancel the intermittent call; // use setInterval () to set a 5-second timer; var num = 0; // set the start second; var max = 5; // Set the termination second; setInterval (function () {num ++; // incrementing num; if (num = max) {clearInterval (this); // cancel the call interval, this indicates the method itself; the ID of the call that has been tracked at intervals; alert ('pop-up after five seconds ') ;}, 1000 );

// Generally, it is the best mode to simulate the interval call by using the time-out call. // The ID is canceled based on the situation because the call interval may cause synchronization problems; the next intermittent call may be started before the end of the previous intermittent call; var num = 0; var max = 5; function box () {num ++; if (num = max) {alert (pop-up window in five seconds);} else {setTimeout (box, 1000); // execute another timeout call every other second; }}; setTimeout (box, 1000); // execution timer; // PS: when a time-out call is used, there is no need to track the ID of the time-out call, because after each execution, if another time-out call is no longer set, the call is automatically stopped;

2. location object

Location is one of BOM objects. It provides information related to the documents loaded in the current window and provides some navigation functions;
In fact, the location object is the property of the window object and also the property of the document object;
Alert (location); // Obtain the current URL

(1) properties of the location object
URL content of the property description
Hash if this part exists, it indicates the anchor part;
Host name: port number;
Hostname host name;
The entire href URL;
Pathname path name;
Port number;
Protocol section;
The query string ('? Gws_rd = ssl # safe = strict & q = AB '). This string starts with a question mark;
(2) method of location object
Assign () redirects to the specified page, which is equivalent to href;
Reload () reload the current URL;
Replace () replaces the current page with a new URL;

Location. hash = '# 1'; // string after setting #, and jump;
Location. hostname = 'Jack'; // Set the host name;
Location. search = '? Id = 5'; // set? String;

// In Web development, we often need to obtain? Id = 5 & search = OK the key-value pair of this type of URL; // Through location, we can write a function to get it one by one; function getArgs () {// create an array for storing key-value pairs; var args = []; // remove? No.; var qs = location. search. length> 0? Location. search. substring (1): ''; // split the array by & string; var items = qs. split ('&'); var item = null, name = null, value = null; // Traverse for (var I = 0; I
 
  

The code is as follows:


Location. assign ('http: // www.baidu.com '); // jump to the specified URL; 2
Location. reload (); // The most effective reload, possibly from the cache;
Location. reload (true); // force load, reload from the server source; 5
Looin. replace ('http: // www.baidu.com '); // jump to the Baidu page on this page, and avoid generating jump history;

3. history object

The history object is the property of the window object. it stores the user's online records, starting from the moment the window is opened;

(1) attributes of the. history object

Length the number of records in the history object;
(2) methods of the history object
Back () to the current URL of the browser history bar, similar to back;
Forward () goes to the next URL of the browser's historical entries, similar to forward;
Go (num) browser goes forward or backward in the history object;

The code is as follows:


Function back (){
History. back ();
}
Function forward (){
History. forward ();
}
Function go (num ){
History. go (num );
}
// PS: you can judge history. length = 0 to check whether there are historical records;

Summary

The Browser Object Model (BOM) is based on the window object, indicating the browser window and visible area of the page;
At the same time, the window object is still the Global object in ECMAScript. Therefore, all Global variables and functions are their attributes, and all native constructors and other functions exist in their namespaces;
(1). you can use the location object to access the browser's navigation system through programming. you can set the corresponding properties to modify the browser URL segment by segment or whole;
(2) you can call the replace () method to navigate to a new URL, which will replace the page currently displayed in the browser history;
(3). screen object: stores information related to the client display, which is generally only used for site analysis;
(4 ). history object: Opens a small gap for accessing the browser's historical records. developers can determine the number of historical records and navigate back or forward to any page in the historical records;

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.