第八章 BOM
window 对象 所有在全局作用域中声明的变量、函数都会变成window 对象的属性和方法
如果页面中包含框架,则每个框架都拥有自己的window 对象,并且保存在frames 集合中。在frames
集合中,可以通过数值索引(从0 开始,从左至右,从上到下)或者框架名称来访问相应的window 对
象。每个window 对象都有一个name 属性,其中包含框架的名称。top 对象始终指向最高(最外)层的框架,也就是浏览器窗口
使用下列代码可以跨浏览器取得窗口左边和上边的位置。
var leftPos = (typeof window.screenLeft == “number”) ?
window.screenLeft : window.screenX;
var topPos = (typeof window.screenTop == “number”) ?
window.screenTop : window.screenY;虽然最终无法确定浏览器窗口本身的大小,但却可以取得页面视口的大小,如下所示。
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;
}
}//等同于< a href="http://www.wrox.com" target="topFrame"></a>
window.open("http://www.wrox.com/", "topFrame");
如果给window.open()传递的第二个参数并不是一个已经存在的窗口或框架,那么该方法就会根
据在第三个参数位置上传入的字符串创建一个新窗口或新标签页。如果没有传入第三个参数,那么就会
打开一个带有全部默认设置(工具栏、地址栏和状态栏等)的新浏览器窗口(或者打开一个新标签页—
—根据浏览器设置)。在不打开新窗口的情况下,会忽略第三个参数。间歇调用和超时调用
超时调用:
//不建议传递字符串!
setTimeout("alert('Hello world!') ", 1000);
//推荐的调用方式
setTimeout(function() {
alert("Hello world!");
}, 1000);
间歇调用:
var num = 0;
var max = 10;
var intervalId = null;
function incrementNumber() {
num++;
//如果执行次数达到了max 设定的值,则取消后续尚未执行的调用
if (num == max) {
clearInterval(intervalId);
alert("Done");
}
}
intervalId = setInterval(incrementNumber, 500);获得查询的每一项参数
<html>
<head>
<script type="text/javascript">
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;
}
var args = getQueryStringArgs();
alert(args["q"]); //"javascript"
alert(args["num"]); //"10"
</script>
</head>
<body>
</body>
</html>
s
9. 跳转 location.assign(“http://www.wrox.com“);
等价于window.location = “http://www.wrox.com“;
location.href = “http://www.wrox.com“;
10. 在调用replace()方法之后,用户不能回到前一个页面,来看下面的例子:
<!DOCTYPE html>
<html>
<head>
<title>You won't be able to get back here</title>
</head>
<body>
<p>Enjoy this page for a second, because you won't be coming back here.</p>
<script type="text/javascript">
setTimeout(function () {
location.replace("http://www.wrox.com/");
}, 1000);
</script>
</body>
</html>
如果将这个页面加载到浏览器中,浏览器就会在1 秒钟后重新定向到www.wrox.com。然后,“后退”
按钮将处于禁用状态,如果不重新输入完整的URL,则无法返回示例页面。
- reload(),作用是重新加载当前显示的页面。如果调用reload()时不传递任何参数,页面就会以最有效的方式重新加载
- //后退一页
history.go(-1);
//前进一页
history.go(1);
//前进两页
history.go(2);
//后退一页
history.back();
//前进一页
history.forward();