BOM( Browser object model ) Mainly used to manage browser windows , It provides a lot of independent 、 Functions that can interact with browser windows , These features have nothing to do with any web content . Browser window window The object is BOM The top object of , Other objects are children of the object .

1.1 Use window object

window The object is BOM At the heart of , Represents an instance of a browser window . All variables and functions declared in the global scope are also window Properties and methods of objects .

1.1.1  Access browser window

adopt window Objects can be accessed in the browser window .

A brief description of the browser object is as follows :

window

client JavaScript Top objects in .

navigator

Contains client information about the browser .

screen

Contains information for the client display .

history

Contains browser window access to URL Information .

location

Contains the document of the current web page URL Information .

document

Including the whole HTML file , Can be used to access document content , And all of its page elements .

1.1.2 Global scope

client JavaScript The code runs in a global context ,window Object provides global scope .

The following usage :

var a = ' I'm a programmer ';
window.b = 'window.b';
c = ' I like js';
document.write(delete window.a);
document.write(delete window.b);
document.write(delete window.c + '<br>');
document.write(window.a);
document.write(window.b);
document.write(window.c);

Use var Statement to declare global variables ,window For this property, a ‘configgurable’ Characteristics of .

1.1.3  Use system testing methods

window Object defines 3 Personal computer interaction Interface method :

  1. alert(): Simple prompt dialog , Prompt information will pop up to users by browser . The method contains an optional prompt parameter .

  2. confirm(): Simple prompt dialog , Prompt information will pop up to users by browser . However, the dialog box that pops up with this method contains two buttons ,‘ confirm ’ and ‘ Cancel ’.

  3. prompt(): The prompt dialog box pops up , It can receive information from users , And return the user's input information to .

usage 1:

var user = prompt(' Please enter your user name :');
if (!!user) {
var ok = confirm(' The user name you entered is :\n' + user + '\n Please make sure the .');
if (ok) {
document.write(' Welcome :\n' + user);
} else {
user = prompt(' Please re-enter your user name :');
document.write(' Welcome :\n' + user);
}
} else {
user = prompt(' Please enter your user name :');
}

this 3 Receive only plain text messages , Users can only use spaces 、 Line breaks and various symbols are used to format the displayed text in the prompt dialog box . Different browsers for this 3 The two dialog boxes display slightly different .

usage 2

window.alert = function (title, info) {
var box = document.getElementById('alert_box');
var html = '<dl><dt>' + title + '</dt><dd>' + info + '</dd><\/dl>';
if (box) {
box.innerHTML = html;
box.style.display = 'block';
} else {
var div = document.createElement('div');
div.id = 'alert_box';
div.style.display = 'block';
document.body.appendChild(div);
div.innerHTML = html;
}
}
alert(' I'm a programmer ', ' I like Js!');

1.1.4 Control window position

Use window Object's moveTo() and moveBy() Method can precisely move the window to a new location . These two methods take two parameters , among moveTo() It's in the new location x and y Coordinate value , and moveBy() Received is the number of pixels moving horizontally and vertically .

The following usage :

window.moveTo(0, 0);
window.moveBy(0, 100);
window.moveTo(200, 300);
window.moveBy(-50, 0);

1.1.5 Use timer

window Object contains 4 This is a timer specific method , Using them, you can run it at a bad time , Avoid continuous operation . You can design animation .

1. setTimeout() Method

Definition :

setTimeout() Method is used to call functions or compute expressions after specified milliseconds. .

grammar :

var o=setTimeout(code,millisec)

Parameters :

code ( It's necessary . Code string to delay execution .)
millisec It's necessary . The number of milliseconds to wait before executing the code .)


The following usage :

var o = document.getElementsByTagName('body')[0].childNodes;
for (var i = 0; i < o.length; i++) {
o[i].onmouseover = function (i) {
return function () {
f(o[i]);
}
}(i);
}
function f(o) {
var out = setTimeout(function () {
document.write(o.tagName);
}, 500);
}

2. clearTimeout() Method

Definition :

clearTimeout() Method can be cancelled by setTimeout() Method set timeout.

grammar :

clearTimeout(id_of_settimeout)

Parameters :

id_of_settimeout( from setTimeout() Back to ID value . This value identifies the block of deferred execution code to cancel .)

The following usage :

var o = document.getElementsByTagName('body')[0].childNodes;
for (var i = 0; i < o.length; i++) {
o[i].onmouseover = function (i) {
return function () {
f(o[i]);
}
}(i);
o[i].onmouseout = function (i) {
return function () {
clearTimeout(o[i].out);
}
}(i);
}
function f(o) {
o.out = setTimeout(function () {
document.write(o.tagName);
}, 500);
}

3. Setlnterval() Method

Definition :

setInterval() Method according to the specified period ( In milliseconds ) To call a function or evaluate an expression .

setInterval() Methods will call functions all the time , until clearInterval() Called or window closed . from setInterval() Back to ID Value can be used as clearInterval() Method parameters .

grammar :

setInterval(code,millisec[,"lang"])

Parameters :

code( It's necessary . Function to call or code string to execute .)

millisec( must . To execute or call periodically code Time interval between , In milliseconds .)

The following usage :

var t = document.getElementsByTagName('input')[0];
var i = 959;
var out = setInterval(f, /*24 * 60 * 60 */ 1000);
function f() {
t.value = i--;
if (i <= 0) {
crearTimeout(out);
document.write(' The Winter Olympics have arrived !');
}
}

In animation design ,setInterval() Method is suitable for continuous execution of an action in an uncertain time , and setInterval() The method is suitable for performing animations that can determine the start and end points in a limited time .

1.2 Use navigator object

navigator Object contains the basic information of the browser , Such as the name 、 Version and system, etc . Use its properties to read basic client information .

1.2.1 Browser detection method

There are many ways to detect browsers .

Common methods include 2 Kind of :

Feature detection

String detection

1.  Feature detection

Feature detection method is based on whether the browser supports specific functions to determine the way of operation .

The following usage :

if (document.getElementsByName) {
var a = document.getElementsByName('p');
} else if (document.getElementsByTagName) {
var a = document.getElementsByTagName('p');
}

2.  character string Detection method

Use the user agent string to detect the browser type .

The following usage :

var s = window.navigator.userAgent;
console.log(s);

1.2.2 Test plug-in

have access to navigator Object's plugins attribute Realization . and plugins Is an array .

Each item in the array contains the following properties :

name

The name of the plug-in .

description

Description of the plug-in .

filename

The file name of the plug-in .

length

What the plug-in does MIME type .

The following usage :

function hasPlugin(name) {
name = name.toLowerCase();
for (var i = 0; i < navigator.plugins.length; i++) {
if (navigator.plugins[i].name.toLowerCase().indexOf(name) > -1) {
return true;
}
}
return false;
}
document.write(hasPlugin('Flash'));
document.write(hasPlugin('QuickTime'));
document.write(hasPlugin('Java'));

1.3 Use location object

location object Store information about the location of the current page , Represents... Of the currently displayed document Web Address . Use location object , Combined with string method, we can extract URL The parameter value of the query string in .

usage 1:

var queryString = function () {
var q = location.search.substring(1);
var a = q.split('&');
var o = {};
for (var i = 0; i < a.length; i++) {
var n = a[i].indexOf('=');
if (n == -1) continue;
var v1 = a[i].substring(o, n);
var v2 = a[i].substring(n + 1);
o[v1] = unescape(v2);
}
return o;
}; var f1 = queryString();
for (var i in f1) {
document.write(i + '=' + f1[i]);
}

usage 2 The jump page .

location = 'http://www.bj-xinhua.com/?bdpz';

1.4 Use history object

      history object Store the browsing history of the browser window , adopt window Object's history Property to access the object . actually ,history Object to store the most recently accessed 、 Limited entry URL Information . In order to protect the security and privacy of client browsing information ,history Object prohibition Js The script directly operates on the access information .

history Object allows the use of length Property in the read list URL The number of , And can call back()、forward() and go() Method Access... In the array URL.

  1. back(): Go back to the previous URL.

  2. forward(): Visit the next URL.

  3. go(): This method is flexible , It can determine the accessibility based on parameters URL.

  • This parameter is a positive integer , The browser will move forward in the history list ; This parameter is a negative integer , The browser moves back in the history list ;
  • The parameter is a string , be history Object to retrieve the... Containing the string from the browsing history URL, And access the first URL.

The following usage :

frames[1].history.back();

1.5 Use screen object

screen object Store client screen information , This information can be used to detect the basic configuration of the client hardware . Meet the display requirements of different users .

The following usage :

function center(url) {
var w = screen.availWidth / 2;
var h = screen.availHeight / 2;
var t = (screen.availHeight - h) / 2;
var l = (screen.availWidth - w) / 2;
var p = 'top=' + t + ',left=' + l + ',width=' + w + ',height=' + h;
var win = window.open(url, 'url', p);
win.focus();
}
center('file:///D:/jsBOM%E6%93%8D%E4%BD%9C/11history.html');

1.6 Use document object

In the browser window , Every widow Objects will contain a document attribute , This property is displayed in the reference window HTML Document document object .

1.6.1 Dynamically generate document content

The following usage :

window.onload = function () {
document.body.onclick = f;
}
function f() {
parent.frames[1].document.open();
parent.frames[1].document.write('<h2> I'm a programmer </h2>');
parent.frames[1].document.close();
}

JavaScriptBOM More articles on operation

  1. JavaScript---Bom Tree operation , Built in methods and built-in objects (window object ,location object ,navigator object ,history object ,screen object )

    JavaScript---Bom Tree operation , Built in methods and built-in objects (window object ,location object ,navigator object ,history object ,screen object ) I. what is the meaning BOM ​      B ...

  2. About DOM The problem of operation and performance optimization of the system - Redraw and rearrange

      Write it at the front : Everybody knows DOM It's expensive to operate . And then where is the price ? One . visit DOM Elements Two . modify DOM Redraw rearrangement caused by One . visit DOM It's like a metaphor in a book : hold DOM and JavaScript( Here it means ECMScri ...

  3. Sql Server series : Partition table operation

    1. Introduction to partition table A partitioned table is logically a table , And physically, it's multiple tables . From the user's perspective , Partitioned tables are the same as regular tables . The main purpose of using partitioned tables is to improve the scalability and manageability of large tables and tables with multiple access modes . Partition table is to set data by ...

  4. C# ini File operations 【 Source download 】

    Introduce C# How to ini Read and write files ,C# You can call [kernel32.dll] In the document  WritePrivateProfileString() and GetPrivateProfileString() Letter ...

  5. js Learning notes : operation iframe

    iframe It's an old topic , And the Internet is basically talking about less use iframe, The reasons are as follows : Blocking page loading . safety problem . Compatibility issues . Search engines can't grab it, etc , But relative to these shortcomings ,iframe It's better , Cross-domain request . ...

  6. jquery and Js Differences and basic operations of

    jqery Grammar and js The grammar is the same , Be regarded as js It's upgraded , These two grammars can be used together , It's just for jqery It is more convenient A page wants to use jqery Words , Let's introduce it first jqery package ,jqery The next package from the Internet is OK , ...

  7. ASP.NET Aries Introductory development tutorial 7:DataGrid Line operations for ( Primary key operation area )

    Preface : Pay close attention to diligence , Keep going , Estimated total 10 This is the end of the series . Last introduction :ASP.NET Aries Introductory development tutorial 6: Format processing and in line editing of list data table This article introduces the primary key operation area related content . 1: When is there a default ...

  8. How to design database operation without lock in high concurrency environment (Java edition )

    An online 2k The game of , It's scary every second . Conventional hibernate It is basically not feasible to insert the library directly . Step by step, I derive a lockless database operation . 1. How to have no lock in concurrency . A very simple idea , Turn concurrency into a single thread .Jav ...

  9. 【 translate 】MongoDB guide /CRUD operation ( Four )

    [ Original address ]https://docs.mongodb.com/manual/ CRUD operation ( Four ) 1 Query plan (Query Plans) MongoDB The query optimizer processes the query and selects a query for a given available index ...

  10. 【 translate 】MongoDB guide /CRUD operation ( 3、 ... and )

    [ Original address ]https://docs.mongodb.com/manual/ CRUD operation ( 3、 ... and ) primary coverage : Atomicity and transactions (Atomicity and Transactions), Reading isolation . Consistency and freshness ...

Random recommendation

  1. oracle---plsql--- Example laobai

    select * from scott.emp; --1 List emp Department number of each department in the table , Maximum wage , minimum wage select deptno,max(sal),min(sal) from scott.emp ...

  2. vuejs overall situation api

    overall situation api set Add array vm.$set Instantiation method overall situation api delete Delete array vm.$delete Instantiation method overall situation api Components component Instantiation method components ...

  3. No module ata_piix found Solutions for

    At one as4u6 Upgrade the kernel to 2.6.18 when , best make install I signed up for one when I was young WARNING: No module ata_piix found for 2.6.18, I didn't care at first , heavy ...

  4. js Achieve a brick in the page drag effect

    use js Implement a brick on the page , But when you click and drag the mouse , Bricks form a drag effect on the page : At the beginning : After mouse click and drag : Implementation code : <html>   <head>       <meta ...

  5. caffe--- Test model classification results and output (python )

    When training a good one model after , We usually do it based on this model The final loss And on the validation set accuracy To judge it . however , For the classification problem , If we only know the overall classification accuracy Obviously not enough , So only know that the model is right ...

  6. front end web Componentization of application ( Two ) Xu Fei

    Web Componentization of application ( Two ) https://github.com/xufei/blog/issues/7 Control platform In the last article, we mentioned the general idea of componentization , This article is mainly about after doing so , What peripheral means do we need ...

  7. java The basis of concurrent programming --- 4.1 Thread Introduction

    One . Thread Introduction What is thread : Now the operating system is running a program , A process is created for it . for example , Start a java Program , The operating system will create a java process . The smallest unit of modern operating system scheduling is thread , It's also called lightweight process , In a process ...

  8. redis series 10 String object

    One . String object encoding Redis String can be stored in 3 Types , They are byte strings (byte string). Integers . Floating point numbers . As mentioned in the previous chapter, the encoding of string objects can be int, raw,embstr. If a string object ...

  9. php Do not use regular expressions to verify ID number verification

    Wrote an ID number verification class. ,php The small white , Writing is not good , You are welcome to give me more comments and suggestions The ID number is divided into four parts. , The first part is before 6 Bit is the address code ,7-14 Bit is the date of birth ,15-17 The number of boys born on the same day in the same place is odd , The girl is me ...

  10. Application monitoring CAT And cat-home Source code reading ( 3、 ... and )

    The last two chapters are from point to point ,cat-client  To   cat-consumer The request processing of , But how can we monitor it for people to see ? Then we need a backstage for the exhibition , That's what this chapter is going to talk about cat-home modular ! belt ...