Home  >  Article  >  Web Front-end  >  Introduction to the use of JavaScript Browser Object Model BOM_Basic knowledge

Introduction to the use of JavaScript Browser Object Model BOM_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:04:241334browse

BOM is also called the browser object model. It provides many objects for accessing browser functions; these functions have nothing to do with any web page content;
BOM lacks specifications, and each browser provider extends it according to its own ideas, so browser shared objects become the de facto standard;

a window object

// BOM的核心对象是window,它表示浏览器的一个实例;
// window对象处于JavaScript结构的最顶层;
// 对于每个打开的窗口,系统都会自动为其定义window对象;
// window对象同时扮演着ECMAScript中Global对象的角色,因此所有在全局作用域中声明的变量/函数都会变成window对象的属性和方法;
// PS:尝试访问未声明的变量会抛出错误,但是通过查询window对象,可以知道某个可能未声明的对象是否存在;
  var newValue = oldValue;        // =>ReferenceError:oldValue is not defined;
  var newValue = window.oldValue;     // =>undefined;

1. Properties and methods of window object
The window object has a series of attributes, which are themselves objects;

(1).Attributes
Attribute Meaning
closed is true when the window is closed;
defaultStatus The default status information displayed in the status bar at the bottom of the window;
The document object currently displayed in the document window;
frames array of frame objects in the window;
history saves the URL recently loaded by the window;
length The number of frames in the window;
location URL in the current window;
name window name;
offscreenBuffering is used to draw new window content and copy existing content after completion to control screen updates;
opener opens the window of the current window;
parent points to the window containing another window (used by the frame);
screen displays screen related information such as height/width (in pixels;)
self indicates the current window;
status describes temporary information in the status bar caused by user interaction;
top Contains the topmost window for 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 and displays a message;
blur() removes focus from the window;
clearInterval(interval) clears the previously set timer interval;
clearTimeOut(timer) clears the previously set timeout;
close() closes the window;
confirm() creates a dialog box that needs to be used for confirmation;
focus() moves the focus to the window;
open(url,name,[options]) opens a new window and returns the new window object;
prompt(text,defaultInput) creates a dialog box asking the user to enter information;
scroll(x,y) scrolls to a pixel position in the window;
setInterval(expression,milliseconds) calculates an expression after a specified time interval;
setInterval(function,millisenconds,[arguments]) calls a function after a specified time interval;
setTimeout(expression,milliseconds)    Compute an expression after the timer expires;
steTimeout(function,milliseconds,[arguments]) calls a function after the timer expires;
print() brings up the print dialog box;
find() brings up the search dialog box;
// For properties and methods under window, you can use window.property, window.method() or direct property or method() calls;
// window.alert(text)=alert(text);

2. System dialog box
The browser calls the system dialog box to display information to the user through the alert()/confirm() and prompt() methods;
The system dialog box has nothing to do with the web page displayed in the browser, and does not contain HTML;
Their appearance is determined by the operating system and/or browser settings, not by CSS;
The dialog boxes opened by these methods are all synchronous and modal; that is to say, the code will stop running when these dialog boxes are displayed, and the code will resume execution after closing these dialog boxes;

// 弹出警告
  alert('警告');

// 确认和取消
  if(confirm('请确定或取消'){          // confirm()本身有返回值;
    alert('您选择了确定');           // 按确定,返回true值;
  })else{
    alert('您选择了取消');           // 按取消,返回false值;
  }

// 输入提示框
  var num = prompt('请输入一个数字',0);     // 第一个参数是文字提示;第二个参数是输入框模式填充值;并返回输入框中的值;
  alert(num);                 // 将prompt()方法返回的值赋给变量num;并弹出;

// 调用打印及查找对话框
  print();                   // 打印; 弹出浏览器打印窗口;
  find();                   // =>boolean;页面有匹配的查找内容返回true;相对于Ctrl+F;

// 状态栏
  defaultStatus = '状态栏默认文本';       // 浏览器底部状态栏初始默认值;
  status = '状态栏文本';            // 浏览器底部状态栏设置值;

3.新建窗口(open())

// 使用window.open()方法可以导航到一个特定的URL,也可以打开一个新的浏览器窗口;
// 它接收四个参数:
// (1).要加载的URL;
// (2).窗口的名称或窗口目标;
// (3).一个特定字符串;
// (4).一个表示新页面是否取代浏览器记录中当前加载页面的布尔值;
open('www.baidu.com'); // chrome-search://local-ntp/www.baidu.com;打开失败;需要添加http://;
open('http://www.baidu.com'); // 新建页面并跳转到百度;
open('http://www.baidu.com','搜索引擎'); // 新建页面 打开百度页面 并命名窗口;并不会自动跳转;并且再次调用时只是刷新那个页面;
open('http://www.baidu.com','_parent'); // 在本页面打开百度;'_blank'是指定新页面打开;
// 第三个字符串参数
设置 值 说明
width 数值 新窗口的宽度,不小于100px;
height 数值 新窗口的高度,不小于100px;
top 数值 新窗口的Y坐标,不能是负值;
left 数值 新窗口的X坐标,不能是负值;
location boolean 是否在浏览器窗口中显示地址栏;不同浏览器默认值不同;
menubar boolean 是否在浏览器窗口显示菜单栏,默认为no;
resizable boolean 是否通过拖动浏览器窗口边框来改变大小;默认no;
scrollbars boolean 如果页面内容显示不下,是否显示滚动条;默认no;
status boolean 是否在浏览器窗口中显示状态栏,默认no;
toolbar boolean 是否在浏览器中显示工具栏;默认no;
fullscreen boolean 浏览器窗口是否最大化;仅IE支持;
open('http://www.baidu.com','baidu','width=400,height=400,top=200,left=200,toolbar=yes');

// open()本身返回window对象
var box = open(); // 返回了一个window对象,打开了一个新空白页面;
box.alert(''); // 然后指定在open()返回的对象打开的新页面弹窗;

// 字窗口操作父窗口
document.onclick = function(){         // 在新的窗口中点击docuement对象;
opener.document.write('子窗口让我输出的!');// 此时在产生它的父窗口会生成文字内容;
}

4.窗口的位置和大小

(1).窗口的位置
// 用来确定和修改window对象(浏览器窗口)相对于屏幕的位置:
// IE+Safari+Opera+Chrome都提供了screenLeft和screenTop属性,
// Firefox提供了screenX和screeY属性;
// 他们分别表示窗口看相对于屏幕左边和上边的位置;
  
// 确定窗口的位置=>IE
  alert(screenLeft);              // 浏览器左侧离屏幕的距离;
// 确定窗口的位置=>Firefox
  alert(screenX);                // 浏览器左侧离屏幕的距离;

// 跨浏览器的方法
  var leftX = (typeof screenLeft == 'number') ? screenLeft : screenX;
  // 判断检测的screenLeft是否是数值,若是则使用screenLeft的值,否则使用screenX的值;

(2).窗口的大小
// 检测浏览器窗口本身及边框的尺寸:outerWidth和outerHeight;
  alert(outerWidth);
  alert(outerHeight);
// 检测页面大小属性:innerWidth和innerHeight;
  alert(innerWidth);
  alert(innerHeight);
// PS:IE没有提供当前浏览器窗口尺寸的属性; 在DOM中有提供相关的方法;

// 在IE及其他浏览器中,提供了:document.documentElement.clientWidth和document.documentElement.clientHeight;来保存页面窗口的信息;
// PS:在IE6中,上述属性在标准模式下才有效;如果是怪异模式,就必须通过document.body.clientWidth和document.body.clientHeight;
// 如果是Firefox等浏览器,直接使用innerWidth和innerHeight;
  var width = window.innerWidth;        // 这里要加window,因为IE会无效;
  var height = window.innerHeight;
  if(typeof width != 'number'){         // IE6浏览器
    if(document.compatMode == 'CSS1Compat'){ // 判断是IE6标准模式;使用documentElement;
      width = document.documentElement.clientWidth;
      height = document.documentElement.clientHeight;
    }else{                  // 否则是IE6非标准模式;使用body;
      width = document.body.clientWidth;
      height = document.body.clientHeight;
    }
  }
  // PS:以上方法可以通过不同浏览器取得各自的浏览器窗口可视部分的大小;
  // document.compatMode可以确定页面是否处于标准模式;
// 调整浏览器位置;
  moveTo(0,0);                 // 移动到(0,0)坐标;IE有效;
  moveBy(10,10);                // 向下和向右分别移动10px;IE有效;

// 调整浏览器大小
  resizeTo(200,200);              // 调整大小;
  resizeBy(200,200);              // 扩展收缩大小;

5.间歇调用和超时调用
1 // JavaScript是单线程语言,但它允许通过设置超时值和间歇时间值来调度代码在特定的时刻执行;
2 // 超时值:在指定的时间过后执行代码;
3 // 间隔值:每隔指定的时间就执行一次代码;

// 超时调用使用window对象的setTimeout()方法;
// 它接受两个参数:要执行的代码和毫秒数;
  setTimeout(function(){            // 直接使用函数传入的方法,扩展性好,性能更加;
    alert('警告!');
  },1000);
// 调用setTimeout()之后,该方法会返回一个数值ID,表示超时调用;
// 这个超时调用的ID是计划执行代码的唯一标识符,可以通过它来取消超时调用;
// 要取消尚未执行的超时调用计划,可以调用clearTimeout()方法并将相应的超时调用ID作为参数传递给它;
  var box = setTimeout(function(){       // 将超时调用的ID赋值给变量box;
    alert('超时调用');
  },1000);
  clearTimeout(box);              // 将ID传入取消调用方法;
// 间歇调用使用window对象的setInterval()方法;
// 它会按照指定的时间间隔重复执行代码,直至间歇调用被取消或页面被卸载;
// 它接收的参数与setTimeout()相同;
  var pox = setInterval(function(){
    alert('间隔调用');
  },1000);
  clearInterval(pox);              // 取消间歇调用;

// 利用setInterval()设置一个5秒的定时器;
  var num = 0;                 // 设置起始秒;
  var max = 5;                 // 设置终止秒;
  setInterval(function(){
    num++;                  // 递增num;
    if(num == max){              
      clearInterval(this);         // 取消间隔调用,this表示方法本身;一直跟踪间隔调用的ID;
      alert('5秒后弹窗');
    }
  },1000);
// 一般使用超时调用来模拟间隔调用是一种最佳模式;
// 因为使用间隔调用需要根据情况来取消ID,并且可能造成同步的一些问题;后一个间歇调用可能会在前一个间歇调用结束之前启动;
  var num = 0;
  var max = 5;
  function box(){
    num++;
    if(num == max){
      alert('5秒后弹窗');
    }else{
      setTimeout(box,1000);          // 隔1秒之后再次执行一个超时调用;
    }
  };
  setTimeout(box,1000);              // 执行定时器; 
  // PS:在使用超时调用时,没必要跟踪超时调用ID,因为每次执行之后,如果不再设置另一个超时调用,调用就会自动停止;

二 location对象

location是BOM对象之一,它提供了与当前窗口中加载的文档有关的信息,还提供了一些导航功能;
事实上,location对象是window对象的属性,也是document对象的属性;
alert(location); // 获取当前的URL

(1).location对象的属性
属性 描述的URL内容
hash 如果该部分存在,表示锚点部分;
host 主机名:端口号;
hostname 主机名;
href 整个URL;
pathname 路径名;
port 端口号;
protocol 协议部分;
search 返回URL的查询字符串('?gws_rd=ssl#safe=strict&q=ab'),这个字符串以问号开头;
(2).location对象的方法
assign() 跳转到指定页面,与href等效;
reload() 重载当前URL;
replace() 用新的URL替换当前页面;

location.hash = '#1'; // 设置#后的字符串,并跳转;
location.hostname = 'Jack'; // 设置主机名;
location.search = '?id=5'; // 设置?后的字符串;

// 在Web开发中,我们经常需要获取诸如?id=5&search=ok这种类型的URL的键值对;
// 通过location,我们可以写一个函数,来一一获取;
  function getArgs(){
    // 创建一个存放键值对的数组;
    var args = [];
    // 去除?号;
    var qs = location.search.length>0?location.search.substring(1):'';
    // 按&字符串拆分数组;
    var items = qs.split('&');
    var item = null, name = null, value = null;
    //遍历
    for(var i = 0; i<items.length; i++){
      item = items[i].split('=');
      name = decodeURIComponent(item[0]);  // 因为查询字符串被浏览器编码过;
      value = decodeURIComponent(item[1]);// 每个查询字符串参数都变成了args对象的属性;
      // 把键值对存放到数组中;
      args[name] = value;
    }
    return args;
  }
  var args = getArgs();
  alert(args['id']);              // 获取URL中id对应的值;

复制代码 代码如下:

location.assign('http://www.baidu.com'); // Jump to the specified URL;2
Location.Reload (); // The most effective reloading, which may be loaded from the cache;
Location.Reload (TRUE); // Forced loading, reload from the server source; 5
locatioin.replace('http://www.baidu.com'); // Jump to the Baidu page on this page and avoid the jump history;

Three history objects

The history object is an attribute of the window object. It saves the record of the user's Internet access, starting from the moment the window is opened;

(1).Properties of history object

length The number of records in the history object;
(2).Methods of history object
back() Go to the previous URL of the browser history entry, similar to back;
forward() Go to the next URL of the browser history entry, similar to forward;
go(num) The browser moves forward or backward in the history object;

Copy code The code is as follows:

Function back(){
        history.back();
}
Function forward(){
         history.forward();
}
Function go(num){
        history.go(num);
}
// PS: You can get whether there is a history record by judging history.length == 0;

Four Summary

The Browser Object Model (BOM) relies on the window object to represent the browser window and the visible area of ​​the page;
At the same time, the window object is also a Global object in ECMAScript, so all global variables and functions are its properties, and all native constructors and other functions also exist in its namespace;
(1). Use the location object to access the browser's navigation system programmatically; set the corresponding attributes to modify the browser's URL segment by segment or as a whole;
(2). Call the replace() method to navigate to a new URL, and the URL will replace the page currently displayed in the browser history;
(3).screen object: saves 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 history. Developers can judge the number of history records based on this, and can also navigate backward or forward to any page in the history;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn