JavaScript学习笔记(九)---- BOM

  • window对象----BOM的核心
  • 控制窗口、框架和弹出窗口
  • 利用location对象中的页面信息
  • 使用navigator对象

(一)window对象

在浏览器中,window对象有双重角色:既是通过Javascript访问浏览器窗口的一个接口,又是ECMAScript规定的Global对象。

1.全局作用域

在全局作用域中声明的变量、函数都会变成window对象的属性和方法。

var age = 29;
function sayAge(){
    alert(this.age);
}
alert(window.age); //29
sayAge(); //29
window.sayAge();//29
View Code

   注意两点:

  1)定义全局变量与window对象上直接定义属性的差别  

var age = 29;
window.color = "red"; 
  • 全局变量不能通过delete操作符删除
var deleAge = delete window.age;
alert(deleAge); //false
alert(window.age); //29
  • 直接在window对象上定义的属性可以使用delete操作符删除
var deleColor = delete window.color;
alert(deleColor); //true
alert(window.color); //undefined

使用var语句添加的window属性有一个名为[[Configurable]]的特性,这个特性的值被设置为false,因此不可以通过delete操作符删除。

   2)尝试访问未声明的变量会抛出错误,但是通过查询window对象,可以知道某个可能未声明的变量是否存在。   

var newValue = oldValue;
alert(newValue); //ReferenceError: oldValue is not defined
var newValue = window.oldValue;
alert(newValue); //null

2.窗口关系及框架

  top对象始终指向最外围的框架,也就是整个浏览器窗口。

  parent对象表示包含当前框架的框架。

  self对象则回指window。

所有这些对象都是window对象的属性,都可以通过window.parent、window.top等形式来访问。

3.窗口位置

  • screenLeft 和 screenTop属性

   分别表示窗口相对与屏幕左边和上边的位置。IE、Safari、Opera和Chrome提供了该属性。

  • screenX 和screenY属性 

   Firefox提供了该属性,Safari和Chrome也同时支持这个属性。

  兼容性考虑:跨浏览器取得窗口左边和上边的位置代码,如下

var leftPos = (typeof window.screenLeft=="number")? window.screenLeft:window.screenX;
var topPos = (typeof window.screenTop == "number")? window.screenTop:window.screenY;

alert("LeftPos:"+ leftPos); //0
alert("TopPos:"+ topPos); //0

4.窗口大小

跨浏览器确定一个窗口的大小不是一件简单的事。

IE9+、FireFox、Safari、Opera和Chrome均为此提供了4个属性:innerWidth、innerHeight、outerHeight、outerWidth。

  • outerWidth 和 outerHeight

   在IE9+、FireFox 和 Safari 中,返回浏览器窗口本身的尺寸。

   在Opera中,这两个属性的值表示页面视图容器的大小。

  • innerWidth 和 innerHeight

    表示该容器中页面视图区的大小(减去边框宽度)。

  • document.documentElement.clientWidth 和 document.documentElement.clientHeight 

   在IE、Firefox、Safari、Opera 和 Chrome中,取得页面视口的大小。

  • document.body.clientWidth和clientHeight

   在混杂模式下的Chrome,通过该属性取得视口的大小。

取得视口大小的代码:

document.compatMode 用来判断当前浏览器采用的渲染方式;CSS1Compat表示标准兼容模式开启,BackCompat表示标准兼容模式关闭
var pageHeight = window.innerHeight;
var pageWidth = window.innerWidth;
//alert(pageHeight +" "+ pageWidth); //undefined undefined

//alert(document.compatMode); //CSS1Compat
if(typeof pageHeight !="number"){    
    if(document.compatMode == "CSS1Compat"){ 
        pageHeight = document.documentElement.clientHeight;
        pageWidth = document.documentElement.clientWidth;
    }else{
        pageHeight = document.body.clientHeight;
        pageWidth = document.body.clientWidth;
    }
}
    
alert("Height:"+pageHeight+"; Width:"+pageWidth);    //Height:402;Width:954

5.导航和打开窗口

  • window.open()

   可以接收4个参数:要加载的URL、窗口目标、描述新窗口特性字符串、新页面是否取代浏览器历史激励中当前加载页面的布尔值。

<body>
      <p>
          This will open a new window/tab:
        <input type="button" value="Go to w3school" onclick="window.open('http://www.w3school.com.cn/')"/>
    </p>
    <p>
        This will open in the current window/tab:
        <input type="button" value="Go to w3school" onclick="window.open('http://www.w3school.com.cn/','_self')">
    </p>
    <p>
        This will open a small new  window/tab:
        <input type="button" value="Go to w3school" onclick="window.open('http://www.w3school.com.cn/','','height=400,width=400,top=10,left=10,resizable=yes')">
    </p>
</body>
  •  window.resizeTo(width,height) 和 window.moveTo(left,top)
function openNewWindow(){
    var newWin = window.open('http://www.w3school.com.cn','','top=50,width=300,height=300,left=50');
    newWin.resizeTo(600,600); //窗口大小600*600
    newWin.moveTo(100,0); //窗口位置左100,上0
}
openNewWindow();
  • window.resizeBy(widthIncrease,heightIncrease) 和 window.moveTo(leftIncrease,topIncrease)
function openNewWindow(){
    var newWin = window.open('http://www.w3school.com.cn','','top=50,width=300,height=300,left=50');
    newWin.resizeBy(600,600); //在原来300*300的基础上增加了(600,600) -> (900,900)
    newWin.moveBy(100,0); //在(50,50)的基础上移动了(100,0)->(150,50)
}
openNewWindow();
  • 使用try...catch块儿检测window.open()弹出的窗口是否被屏蔽
var blocked = false;
try{
    var win = window.open('http://www.w3school.com.cn','_blank');
    if(win==null){
        blocked = true;
    } 
}catch(ex){
     blocked=true;
}
if(blocked){
     alert("The popup was blocked");
}

6.间歇调用和超时调用

Javascript是单线程语言,但它允许通过设置超时值(在指定的时间过后执行代码)和间歇值(每隔指定的时间就执行一次代码)来调度代码在特定的时刻执行。

  • 超时调用:window对象的setTimeout()方法

  两个参数:第一个参数要执行的代码,可以是字符串(就和eval( )执行函数中使用的字符串一样),也可以是一个函数,可以直接传入函数名字。第二个参数以毫秒表示的时间(即在执行代码前需要等待多少毫秒)。

  例如:在一秒钟后显示一个警告框

setTimeout(function(){
    alert("hello world");
},1000);

  注意:正因为Javascript是单线程的解释器,因此一段时间内只能执行一段代码。setTimeout()的第二个参数告诉Javascript再过多长时间把当前任务添加到队列中。如果队列是空的,就立即执行;如果队列非空,那就等前面的代码执行完了以后再执行。

  调用setTimeout()之后,该方法返回一个数值ID,表示超时调用。超时调用ID是计划执行代码的唯一表示符,可以通过它来取消超时调用。

var timeoutId = setTimeout(function(){
    alert("hello world");
},3000);
clearTimeout(timeoutId);
View Code
  • 间歇调用:window对象的setInterval()方法

    与setTimeout()方法类似。

例如:每个5秒弹出一个提示。

setInterval(function(){
    alert("hello world!");
},5000);

调用setInterval()方法同样也会返回一个间歇调用ID,该ID可用于在将来的某个时刻取消间歇调用。取消间歇调用的重要性要远远高于取消超时调用,因为在不加干涉的情况下,间歇调用将会一直执行到页面卸载。

例如:如果执行次数达到了max设定的值,则取消后续尚未执行的调用

var num = 0;
var max = 10;
function incrementNumber(){
    num++;
    if(num == max){
        clearInterval(intervalId);
        alert("Done");
    }
}
intervalId = setInterval(incrementNumber,500);

同样,使用setTimeout()方法,完成该操作

var num = 0;
var max = 10;
function incrementNumber(){
    num++;
    if(num < max){
        setTimeout(incrementNumber,500);        
    }else{
        alert("Done");
    }
}
setTimeout(incrementNumber,500);
View Code

7.系统对话框

 浏览器通过alert()、confirm()和prompt()方法可以调用系统对话框向用户显示消息。

  • 对话框的外观有操作系统或浏览器设置决定,而不是由CSS决定。
  • 显示这些对话框的时候代码会停止执行,而关掉这些对话框后代码又会恢复执行。
var result = prompt("hello",'');
if(result!=null){
    alert("hello "+ result);
}
  • window.find()相当于Ctrl+F查找
  • wind.print()弹出打印配置页面

(二)location对象

location是最有用的BOM对象之一,它提供了与当前窗口中加载的文档有关的信息,还提供了一下导航功能。

  • location对象既是window对象的属性,也是document对象的属性。换句话说,window.location和document.location引用的是同一个对象。
  • location将URL解析为独立的片段,让开发人员通过不同的属性访问这些片段。
  • location对象的所有属性:

 假设初始URL为http://www.baidu.com/

(1)将URL修改为http://www.baidu.com/#section1

location.hash = "#section1";

(2)将URL修改为http://www.baidu.com/?q=javascript

location.search = "?q=javascript";

(3)将URL修改为http://www.yahoo.com.cn

location.hostname = "www.yahoo.com.cn";

(4)将URL修改为http://www.baidu.com/mydir

location.pathname = "mydir";

(5)将URL修改为http://www.baidu.com:8080

location.port = 8080
  • 每次修改location属性(hash除外),页面都会以新URL重新加载。
  • 通过上述任何一种方式修改URL之后,用户通过单击“后退”按钮都会导航到前一个页面。要禁用这种行为可以使用replace()方法。

replace()方法:

setTimeout(function(){
        location.replace("http://www.w3school.com.cn/");        
    },3000);

(三)navigator对象

 包含诸多属性,用于识别客户端浏览器的信息等。

alert(navigator.appCodeName); //Mozilla
    alert(navigator.appName);//firefox/chrome-->Netscape;IE-->Micrsoft Internet Explorer;
    alert(navigator.cookieEnabled);//true/false

1.检测插件

 检测浏览器中是否安装了特定的插件式一种最常见的检测用法。

 1)对于非IE浏览器,使用plugins数组来达到这个目的。数组中的每一项都包含下列属性:

    name:插件的名字。

    description:插件的描述。

    filename:插件的文件名。

    length:插件所处理的MIME类型数量。

        例如:输出Firefox中安装的所有插件信息

    for(var i=0;i<navigator.plugins.length;i++){
        document.write("name: "+navigator.plugins[i].name+"<br/>"+
                       "description: "+navigator.plugins[i].description+"<br/>"+
                       "filename: "+navigator.plugins[i].filename+"<br/>"+
                       "length: "+navigator.plugins[i].length+"<br/>"
                       );        
        document.write("<br><hr/>");
    }

  输出结果:

例如:检测浏览器中是否安装了某插件(在IE中无效),在Firefox、Safari、Opera和Chrome中可以使用这种方法来检测插件。

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;
            }
        }
    }

        //检测Flash插件
        alert(hasPlugin("Flash"));//true

循环迭代每个插件并将插件的name与给定的名字进行比较。

  2)检测IE中的插件

   IE不支持Netscape式的插件。在IE中检测插件的唯一方式就是使用专有的ActiveXObject类型,并尝试创建一个特定的插件的实例。IE是以COM对象的方式实现插件的,而COM对象使用唯一标示符来识别。因此,要想检查特定的插件,就必须知道其COM标识符。

  例如:检测IE中的插件

function hasIEPlugin(name){
    try{
        new ActiveXObject(name);
        return true;
    }catch(ex){
        return false;
    }
}
alert(hasIEPlugin("ShockwaveFlash.ShockwaveFlash"));

(四)screen对象

screen对象基本上只用来表明客户端的能力,其中包括浏览器窗口外部的显示器的信息,如像素宽度和高度等。

alert(screen.availWidth+"*"+screen.availHeight); //1280*984

(五)history对象

history对象保存着用户上网的历史记录,从窗口被打开的那一刻算起。

  • go()方法

  go()接受一个参数,表示向后或向前跳转的页面数的一个整数值。负数表示向后跳转,正数表示向前跳转。  

history.go(-1); //后退一页
history.go(2);  //向前两页
  • back():后退一页
history.back();
  • forward():前进一页
history.forword();
  • length属性:保存历史记录的数量

 history.length等于0,表示用户打开窗口的第一个页面。

posted @ 2014-09-09 10:48  Immanuely  阅读(164)  评论(0编辑  收藏  举报