第八章 BOM

第八章 BOM

  • W3C为了把浏览器中JS最基本的部分标准化,已经将BOM纳入了H5的规范中

8.1 window对象

  • window对象具有双重角色,即使ECMAScript规定的Global对象,就是JS访问浏览器窗口的一个接口

8.1.1 全局作用域

var age = 29;
function sayAge(){
    console.log(this.age);
}
console.log(window.age); //29
console.log(sayAge()); //29
console.log(age); //29
  • 区别:

    • 全局变量不能delete,window对象上定义的属性可以
    • 访问未声明的变量:全局会报错,window对象不会
    var newVal = oldVal; //error
    var newVal = window.oldVal; //undefined
    

8.1.2 窗口关系及框架

  • 如果页面包含框架,则每个框架都有自己的window对象,并保持在frames集合中
  • 访问方式
    • frames[index] 或 frames[name]
    • window.frames[index] 或 window.frames[name]
    • 推荐:top.frames[index] 或 top.frames[name]
    • top始终指向最外层的框架,而window对象指向本身特定框架实例
  • 父对象 parent
    • parent始终指向当前框架的直接上层框架
    • parent在最外层时等于top

8.1.3 窗口位置

  • 浏览器宽口距离相对于屏幕左边和上边的位置(各浏览器差异大)
var leftPos = (typeof window.screenLeft == "number")?window.screenLeft:window.screenX;
var topPos = (typeof window.screenTop == "number")?window.screenTop:window.screenY;
  • 但是moveTo() moveBy() 可以精确移动
    • moveTo()参数:新位置x和y
    • moveBy()参数:水平和垂直方向上移动的像素
window.moveTo(200,200);//移动到屏幕200px*200px坐标
window.moveBy(0,100); //向下移动100px

8.1.4 窗口大小

  • innerWidth innerHeight outerWidth outerHeight
  • 虽然无法确定浏览器窗口本身的大小,但可以取得页面视口的大小
var pageWidth = window.innerWidth,
    pageHeight = window.innerHeight;
if(typeof pageWidth != "number"){
    if(document.compatMode == "CSS1Compat"){
        //标准模式
        pageWidth = document.documentElement.clientWidth;
        pageHeight = document.documentElement.clientHeight;
    }else{
        //混杂模式
        pageWidth = document.body.clientWidth;
        pageHeight = document.body.clientHeight;
    }
}
  • resizeTo() resizeBy() 调整浏览器大小
window.resizeTo(100, 100); //调整到100x100
window.resizeBy(100, 100); //扩大100x100

8.1.5 导航和打开窗口

弹出窗口
window.open("http://www.baidu.com", "targetFrame", params , true); //boolean是否新窗口打开
  • targetFrame 如果有则在该框架名中打开,如果没有则创建targetFrame
  • targetFrame可以是 "_self" "_parent" "_top" "_blank"
var newWin = window.open("http://www.baidu.com", "newFrame", "height=400,width=400,top=10,left=10,resizable=yes" , true); //boolean是否新窗口打开
newWin.resizeTo(500, 500);
newWin.moveTo(100, 100);
newWin.close();
alert(newWin.closed); //true
alert(newWin.opener == window); //true
  • 新标签页单独运行 切断与打开它的标签页通信
newWin.opener == null;
安全限制
弹出窗口被屏蔽检测方法
var blocked = false;
try{
    var newWin = window.open("http://www.baidu.com","_blank");
    if(newWin == null){
        //被浏览器内置屏蔽程序阻止
        blocked = true; 
    }
}catch(ex){
    //被浏览器扩展或其他程序阻止
    blocked = true;
}
if(blocked){
    alert("The popup was blocked")
}

8.1.6 间歇调用和超时调用

  • 超时调用
var timeoutId = setTimeout(function(){
    console.log('Hello World');
},1000)
clearTimeout(timeoutId);
  • 间歇调用 (不推荐 因为后一个会在前一个结束前启动)
var num=0, max=10;
var intervalId = null;
function addNum(){
    console.log('-->', num);
    num++;
    if(num == max){
        clearInterval(intervalId);
    }
}
intervalId = setInterval(addNum,1000);

8.1.7 系统对话框

  • alert() 警告
  • confirm() 确认
if(confirm('Are you sure?')){
    console.log('yes');
}else{
    console.log('no');
}
  • prompt() 提示
var res = prompt("请输入姓名","");
if(res!=null){
    alert("欢迎您!"+res);
}
  • 查找 window.find()
  • 打印 window.print()

8.2 location对象

  • 最有用的BOM对象之一

  • 既是window对象属性,也是document对象属性

  • location对象保存url解析独立字段

    属性名 说明
    hash 返回url中的hash(#号跟0或多个字符)
    host 服务器名称和端口号
    hostname 服务器名
    href 当前页完整url 相当于location.toString()
    pathname 返回url中的目录或文件名
    port 端口号
    protocal 页面协议
    search 返回url的查询字符串 以问号开头
console.log('-->location.hash: ',location.hash);
console.log('-->location.host: ',location.host);
console.log('-->location.hostname: ',location.hostname);
console.log('-->location.href: ',location.href);
console.log('-->location.pathname: ',location.pathname);
console.log('-->location.port: ',location.port);
console.log('-->location.protocal: ',location.protocal);
console.log('-->location.search: ',location.search);

8.2.1 查询字符串参数

function getQueryStringArgs(){
    //get query string without the initial ?
    var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
    
        //object to hold data
        args = {},
    
        //get individual items
        items = qs.length ? qs.split("&") : [],
        item = null,
        name = null,
        value = null,
        
        //used in for loop
        i = 0,
        len = items.length;
    
    //assign each item onto the args object
    for (i=0; i < len; i++){
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        
        if (name.length){
            args[name] = value;
        }
    }
    
    return args;
}

//assume query string of ?q=javascript&num=10

var args = getQueryStringArgs();

alert(args["q"]);     //"javascript"
alert(args["num"]);   //"10"

8.2.2 位置操作

  • location.assign()
location.assign("http://www.baidu.com");
//等价于
window.location = "http://www.baidu.com";
location.href = "http://www.baidu.com"; //最常用
  • location属性可修改 hash search hostname port pathname
  • locatio.reload() 有可能从缓存中加载 之后的代码有可能不执行所以一般放最后
  • locatio.reload(true) 从服务器重新加载 强制刷新

8.3 navigator对象

  • 识别客户端浏览器的事实标准
属性 描述
appCodeName 返回浏览器的代码名。
appMinorVersion 返回浏览器的次级版本。
appName 返回浏览器的名称。
appVersion 返回浏览器的平台和版本信息。
browserLanguage 返回当前浏览器的语言。
cookieEnabled 返回指明浏览器中是否启用 cookie 的布尔值。
cpuClass 返回浏览器系统的 CPU 等级。
onLine 返回指明系统是否处于脱机模式的布尔值。
platform 返回运行浏览器的操作系统平台。
systemLanguage 返回 OS 使用的默认语言。
userAgent 返回由客户机发送服务器的 user-agent 头部的值。
userLanguage 返回 OS 的自然语言设置。

8.3.1 检测插件

  • 对于非IE浏览器 使用plugins数组 数组中每个对象拥有属性
    • name 插件名称(有时不完全包含插件信息)
    • description 插件描述
    • filename 插件文件名
    • length 插件所处理的MIME类型数量
    • 每个插件对象本身也是一个MimeType数组 含有四个属性
      • description enabledPlugin suffixes后缀 type
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;
        }
    }
}
function hasIEPlugin(name){
    //检测IE中的插件
    try{
        new ActiveXObject(name);
        return true;
    }catch(ex){
        return false;
    }
}

function hasFlash(){
    var result = hasPlugin("Flash");
    if(!result){
        result = hasIEPlugin("ShockwaveFlash.ShockwaveFlash");
    }
    return result;
}

//检查flash
alert(hasFlash());

8.3.2 注册处理程序

  • Firefox2的navigator新增 registerContentHandler()和registerProtocalHandler()
  • 指明站点可以处理特定类型的信息
  • registerContentHandler(要处理的MIME类型,处理该MIME的URL,应用程序名称)
navigator.registerContentHandler("application/rss+xml","http://www.reader.com?feed=%s","reader client");
  • %s表示RSS源URL 浏览器自动插入

  • RSS源的MIME类型

    • application/rss+xml
    • application/atom+xml
    • application/vnd.mozilla.maybe.feed
  • registerProtocalHandler(要处理的协议如ftp或mailto,可以处理该协议的URL,应用程序名称)

navigator.registerProtocalHandler("mailto","http://www.sendmail.com?cmd=%s","mail client");

8.4 screen对象

  • 用处不大
  • 调整窗口大小
window.resizeTo(screen.availWidth, screen.availHeight); //不一定有效
属性 说明
availHeight 返回显示屏幕的高度 (除 Windows 任务栏之外)。
availWidth 返回显示屏幕的宽度 (除 Windows 任务栏之外)。
bufferDepth 设置或返回调色板的比特深度。
colorDepth 返回目标设备或缓冲器上的调色板的比特深度。
deviceXDPI 返回显示屏幕的每英寸水平点数。
deviceYDPI 返回显示屏幕的每英寸垂直点数。
fontSmoothingEnabled 返回用户是否在显示控制面板中启用了字体平滑。
height 返回显示屏幕的高度。
logicalXDPI 返回显示屏幕每英寸的水平方向的常规点数。
logicalYDPI 返回显示屏幕每英寸的垂直方向的常规点数。
pixelDepth 返回显示屏幕的颜色分辨率(比特每像素)。
updateInterval 设置或返回屏幕的刷新率。
width 返回显示器屏幕的宽度。

8.5 history对象

  • history.go(n);
    • n为正数前进
    • 负数后退
    • 不填刷新
    • 字符串则查找最近的含有该字符串网页
  • history.back(); //后退
  • history.forward(); //前进
  • 检查时候第一个页面
if(history.length == 0){
    //这应该是用户打开窗口后的第一个页面
}
  • IE8及更高版本,改变URL中hash 会在浏览器中生成一条新历史记录
posted @ 2019-10-08 17:51  KevinTseng  阅读(99)  评论(0编辑  收藏  举报