JavaScript高级程序设计之window对象

在浏览器中window对象实现了JavaScript中的Global对象;

window对象是最顶层的对象;

所有其他全局的东西都可以通过它的属性检索到。

var a = 5;

window.aa = 10;

// 所有全局变量都可以通过window的属性找到,但不是真正的属性
console.log(window.a);  // 5

// delete操作符只能删除对象的属性,不能删除游离的变量
delete a;
delete aa;

console.log(a);  // 5

console.log(aa);  // error: aa is not defined

window(窗口)的位置

// 获取窗口距离屏幕左上角的位置
var getWinPos = function () {

    return {
        leftPos: (typeof window.screenLeft === "number") ? window.screenLeft : window.screenX,
        topPos: (typeof window.screenTop === "number") ? window.screenTop : window.screenY
    };
};

窗口的大小

// 获取窗口的大小
var getWinSize = function () {

    var width = window.innerWidth,
        height = window.innerHeight;

    if (typeof width !== "number") {
        
        // 标准模式
        if (document.compatMode === "CSS1Compat") {
            width = document.documentElement.clientWidth;
            height = document.documentElement.clientHeight;
        } else {
            width = document.body.clientWidth;
            width = document.body.clientHeight;
        }
    }

    return {
        width: width,
        height: height
    };
};

/*
 * doucment.compatMode 只可能返回两个状态:CSS1Compat, BackCompat;分别表示标准模式和怪异模式
 * 属性早期浏览器大战是留下的hack
*/

弹出窗口window.open

// window.open("http://www.google.com/"); 默认新窗口打开


// 打开一个定制的新窗口到目前窗口
var popWin = window.open("http://www.so.com/", "_blank", "width=400,height=400,top=100,left=100,resizable=yes");

// 在原来位置的基础上作矢量位移
popWin.moveBy(300, 200);

// 检测弹出窗口是否被屏蔽
var isPopWinBlocked = function (url) {
    
    var blocked = false;

    try {
        var popWin = window.open(url);

        if (popWin === null) {
            blocked = true;
        }
    } catch (ex) {
        blocked = true;
    }

    return blocked;
};


if (isPopWinBlocked("http://www.so.com/")) {
    alert("popWin is blocked");
} else {
    alert("ok");
}

 

posted @ 2014-05-29 11:38  farawayfromhome  阅读(329)  评论(0编辑  收藏  举报