window对象
window对象不但充当全局作用域,而且表示浏览器窗口。
window对象有双重角色:既是通过js访问浏览器窗口的一个接口,又是ECMAScript规定的Global对象。
所有在全局作用域中声明的变量、函数都会变成window对象的属性和方法。全局变量不能通过delete操作符删除,而直接在window对象上定义的属性可以。
var age = 29;
window.color = "red";
//throws an error in IE < 9, 在其他浏览器中返回false
delete window.age;
//throws an error in IE < 9, 在其他浏览器中返回true
delete window.color; //returns true
alert(window.age); //29
alert(window.color); //undefined
- 窗口关系
每个框架都有自己的window对象,并且保存在frames集合中。
<head>
<title>Frameset Example</title>
</head>
<frameset rows="160,*">
<frame src="frame.htm" name="topFrame">
<frameset cols="50%,50%">
<frame src="anotherframe.htm" name="leftFrame">
<frame src="yetanotherframe.htm" name="rightFrame">
</frameset>
</frameset>
top对象始终指向最高层的框架,即浏览器窗口。与top相对的另一个window对象是parent。在没有框架的情况下,parent一定等于top
<head>
<title>Frameset Example</title>
</head>
<frameset rows="100,*">
<frame src="frame.htm" name="topFrame">
<frameset cols="50%,50%">
<frame src="anotherframe.htm" name="leftFrame">
<frame src="anotherframeset.htm" name="rightFrame">
</frameset>
</frameset>
- 窗口位置
screenLeft和screenTop属性,分别用于表示窗口相对于屏幕左边和上边的位置。
<body>
<p>This will open a new window/tab:
<input type="button" value="Go to Wrox.com" onclick="window.open('http://www.wrox.com/')"></p>
<p>This will open in the current window/tab:
<input type="button" value="Go to Wrox.com" onclick="window.open('http://www.wrox.com/', '_self')"></p>
</body>
使用moveTo()和moveBy()可以将窗口精确的移动到一个新位置。都是接收2个参数,moveTo()接收的是新位置的x和y坐标值,moveBy()接收的是在水平和垂直方向上移动的像素数。
- 窗口大小
window对象有innerWidth和innerHeight属性,可以获取浏览器窗口的内部宽度和高度。表示该容器中页面视图区的大小,内部宽高是指除去菜单栏、工具栏、边框等占位元素后,用于显示网页的净宽高。
对应的,还有一个outerWidth和outerHeight属性,可以获取浏览器窗口的整个宽高。返回浏览器窗口本身的尺寸。
在Chrome中,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;
}
}
alert("Width: " + pageWidth);
alert("Height: " + pageHeight);
使用resizeATo()和resizeBy()方法可以调整浏览器窗口大小。接收2个参数,resizeTo()接收浏览器窗口的新宽度和新高度,resizeBy()接收新窗口与原窗口的宽度和高度之差。
导航和打开窗口
使用window.open()方法可以导航到一个特定的URL,也可以打开一个新的浏览器窗口。此方法可以接收4个参数:要加载的URL、窗口目标、一个特性字符串、一个表示新页面是否取代浏览器历史记录中当前加载页面的布尔值。
window.open(“http://www.baidu.com/“, “topFrame”)
//等同于
window.open()会返回一个指向新窗口的引用,调用close()方法可以关闭新打开的窗口。新创建的window对象有一个opener属性,保存着打开它的原始窗口对象。
将opener属性设置为null就是告诉浏览器新创建标签页不需要与打开它的标签页通信,可以在独立的进程中进行。
检测弹出窗口是否被屏蔽
var blocked = false;
try {
var wroxWin = window.open("http://www.wrox.com", "_blank");
if (wroxWin == null){
blocked = true;
}
} catch (ex){
blocked = true;
}
if (blocked){
alert("The popup was blocked!");
}
- 间歇调用和超时调用
超时调用需要使用setTimeout()方法,接收2个参数:要执行的代码和以毫秒表示的时间。
//不建议使用!
setTimeout("alert('Hello world!') ", 1000);
//推荐方法
setTimeout(function() {
alert("Hello world!");
}, 1000);
只要在指定的时间尚未过去之前调用clearTimeout(),就可以完全取消超时调用。
//设置超时调用
var timeoutId = setTimeout(function() {
alert("Hello world!");
}, 1000);
//注意:把它取消
clearTimeout(timeoutId);
超时调用在全局作用域中执行的,因此函数中this值在非严格模式下指向window对象,在严格模式下是undefined。
间歇调用:按照指定的时间间隔重复执行代码,直至被取消或页面被卸载。接收2个参数:要执行的代码和每次执行之前需要等待的毫秒数。
//不建议使用!
setInterval("alert('Hello world!') ", 10000);
//推荐方法
setInterval(function() {
alert("Hello world!");
}, 10000);
要取消尚未执行的间歇调用,可以使用clearInterval()方法并传入相应的间歇调用ID。
var num = 0;
var max = 10;
var intervalId = null;
function incrementNumber() {
num++;
//如果执行次数达到max设定的值,则取消后续尚未执行的调用
if (num == max) {
clearInterval(intervalId);
alert("Done");
}
}
intervalId = setInterval(incrementNumber, 500);
变量num每半秒钟递增一次,递增到最大值时就取消调用。
var num = 0;
var max = 100;
function incrementNumber() {
num++;
//如果执行次数未达到max设定的值,则设置另一次超时调用
if (num < max) {
setTimeout(incrementNumber, 500);
} else {
alert("Done");
}
}
setTimeout(incrementNumber, 500);
- 系统对话框
浏览器通过alert(),confirm(),prompt()方法调用系统对话框向用户显示消息。
- alert():接收一个字符串并将其显示给用户。
- confirm():除了显示OK外,还会显示Cancel取消按钮。
- prompt():提示框,用于提示用户输入一些文本。除了OK和Cancel按钮外,还会显示一个文本输入域,以供用户在其中输入内容。接收2个参数:要显示给用户的文本提示和文本输入域的默认值。
//显示“打印”对话框
window.print();
//显示“查找”对话框
window.find();
location对象
location对象既是window对象的属性,也是document对象的属性。
创建一个函数,用以解析查询字符串,然后返回包含所有参数的一个对象:
function getQueryStringArgs(){
//取得查询字符串并去掉开头的问号
var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
//保存数据的对象
args = {},
//取得每一项
items = qs.length ? qs.split("&") : [],
item = null,
name = null,
value = null,
//在for循环中使用
i = 0,
len = items.length;
//逐个将每一项添加到args对象中
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;
}
//假设查询的字符串是 ?q=javascript&num=10
var args = getQueryStringArgs();
alert(args["q"]); //"javascript"
alert(args["num"]); //"10"
使用location对象可以通过很多方式改变浏览器位置。
- location.assign(“http://www.baidu.com“);
- window.location=”http://www.baidu.com”;
- location.href=”http://www.baidu.com”;
可以通过将hash,search,hostname,pathname,port属性设置为新值来改变URL。通过这些方法修改后,浏览器的历史记录都会生成一条新纪录,用户通过单击“后退”可导航到前一个界面。若要禁用此行为,可使用replace()方法,该方法接收一个参数:要导航到的URL,结果不会在历史记录中生成新纪录。
reload():重新加载当前显示的页面。若要强制从服务器重新加载,方法如下:
location.reload();//有可能从缓存中加载
location.reload(true);//从服务器重新加载
可以用location.href获取。要获得URL各个部分的值,可以这么写:
location.protocol; // 'http'
location.host; // 'www.example.com'
location.port; // '8080'
location.pathname; // '/path/index.html'
location.search; // '?a=1&b=2'
location.hash; // 'TOP'
要加载一个新页面,可以调用location.assign()。如果要重新加载当前页面,调用location.reload()方法非常方便。
navigator对象
navigator对象表示浏览器的信息,最常用的属性包括:
- navigator.appName:浏览器名称;
- navigator.appVersion:浏览器版本;
- navigator.language:浏览器设置的语言;
- navigator.platform:操作系统类型;
navigator.userAgent:浏览器设定的User-Agent字符串。
//检测插件(在IE中无效) function hasPlugin(name){ name = name.toLowerCase(); for (var i=0; i < navigator.mimeTypes.length; i++){ if (navigator.mimeTypes[i].name.toLowerCase().indexOf(name) > -1){ return true; } } return false; } //检测 flash alert(hasPlugin("Flash")); //检测 quicktime alert(hasPlugin("QuickTime")); //detect Java alert(hasPlugin("Java"));
这个例子中hasPlugin()接收一个参数:要检测的插件名。
//检测IE中的插件
function hasIEPlugin(name){
try {
new ActiveXObject(name);
return true;
} catch (ex){
return false;
}
}
//检测 flash
alert(hasIEPlugin("ShockwaveFlash.ShockwaveFlash"));
//检测 quicktime
alert(hasIEPlugin("QuickTime.QuickTime"));
这个例子中hasIEPlugin()只接收一个COM标识符作为参数。
//plugin detection - doesn't work in 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;
}
//plugin detection for IE
function hasIEPlugin(name){
try {
new ActiveXObject(name);
return true;
} catch (ex){
return false;
}
}
//detect flash for all browsers
function hasFlash(){
var result = hasPlugin("Flash");
if (!result){
result = hasIEPlugin("ShockwaveFlash.ShockwaveFlash");
}
return result;
}
//detect quicktime for all browsers
function hasQuickTime(){
var result = hasPlugin("QuickTime");
if (!result){
result = hasIEPlugin("QuickTime.QuickTime");
}
return result;
}
//detect flash
alert(hasFlash());
//detect quicktime
alert(hasQuickTime());
请注意,navigator的信息可以很容易地被用户修改,所以JavaScript读取的值不一定是正确的。很多初学者为了针对不同浏览器编写不同的代码,喜欢用if判断浏览器版本,例如:
var width;
if (getIEVersion(navigator.userAgent) < 9) {
width = document.body.clientWidth;
} else {
width = window.innerWidth;
}
但这样既可能判断不准确,也很难维护代码。正确的方法是充分利用JavaScript对不存在属性返回undefined的特性,直接用短路运算符||计算:
var width = window.innerWidth || document.body.clientWidth;
history对象
history对象保存了浏览器的历史记录,JavaScript可以调用history对象的back()或forward(),相当于用户点击了浏览器的“后退”或“前进”按钮。
使用go()方法可以在用户的历史记录中任意跳转,可以向后也可以向前。
history.go(-1);//后退一页
history.go(1);//前进一页
history.back();//后退一页
history.forword();//前进一页