《JavaScript高级程序设计》笔记:BOM(八)

BOM(浏览器对象模型)提供了很多对象,用于访问浏览器的功能,这些功能与任何网页内容无关。

window对象

全局作用域

定义全局变量与在window对象上直接定义属性还是有一点差别:全局变量不能通过delete操作符删除,而直接在window对象上的定义的属性可以。

var age = 29;
window.color = "red";

delete window.age;
delete window.color;

console.log(window.age); //29
console.log(window.color); // undefined

窗口关系及框架

window.top: 指定最高(最外)层的框架
window.parent:指向当前框架的直接上层框架,在某些情况下,parent有可能等于top

窗口位置

使用下列代码可以跨浏览器取得窗口左边和上边的位置:

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

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

console.log(leftPos);
console.log(topPos);

窗口大小

虽然无法确定浏览器窗口本身的大小,但却可以取得页面视口的大小。

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

}

console.log(pageWidth);
console.log(pageHeight);

location对象

// 将url 修改为"http://www.wrox.com/WileyCAD/#section1"
location.hash = "#section1";

// 将url 修改为"http://www.wrox.com/WileyCAD/?q=javascript"
location.search = "?q=javascript";

// 将url 修改为"http://www.yahoo.com/WileyCAD/"
location.hostname = "www.yahoo.com";

// 将url 修改为"http://www.yahoo.com/mydir/"
location.pathname= "mydir";

// 将url 修改为"http://www.yahoo.com:8090/mydir/"
location.port= 8090;
location.reload(); // 重新加载(有可能从缓存中加载)
location.reload(true); // 重新加载(从服务器重新加载)

navigator对象

检查插件

// 检测插件(在IE中无效)
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;
}

// 检测flash
console.log(hasPlugin("Flash"));

// 检测IE中的插件
    function hasIEPlugin(name){
        try{
            new ActiveXObject(name);
            return true;
        }catch(ex){
            return false;
        }
    }
    
    // 检测flash
    alert(hasIEPlugin("ShockwaveFlash.ShockwaveFlash"));

screen对象

javascript中有几个对象在编程中用处不大,而screen对象就是其中之一。screen对象基本上只用来表明客户端的能力。

history对象

history.go(-1); // 后退一页
history.go(1); // 前进一页
history.go(2); // 前进两页

history.back(); // 后退一步
history.forward(); //前进一步

//确定用户是否一开始就打开了你的页面
if(history.length == 0) {
    // 这应该是用户打开窗口后的第一个页面
}
    原文作者:风雨后见彩虹
    原文地址: https://segmentfault.com/a/1190000000745102
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞