《Javascript高级程序设计》学习笔记八

BOM
 window对象
BOM的核心对象window,它表示浏览器的实例。
全局作用域
在全局作用域中声明的变量,函数都会变成window
对象的属性和方法。
var age=29;
function sayAge(){
  alert(this.age);
}
alert(window.age);//29
sayAge();//29
window.sayAge();//29

//全局变量不能通过delete操作符删除,而直接在window对象上
的定义的属性可以。

var age=29;
window.color="red";
//在IE<9对抛出错误,在其他所有浏览器中都返回false
delete window.age;
//在IE<9对抛出错误,在其他所有浏览器中都返回true;
delete window.age;//returns true

alert(window.age);//29
alert(window.color);//undefined


尝试访问未声明的变量的变量会抛出错误,但是通过查询window对象
可以知道某个可能未声明的变量是否存在。例如:
//这里会抛出错误,因为oldValue未定义
var newValue=oldValue;
//这里不会抛出错误,因为这是一次属性查询
//newValue的值是undefined
var newValue=window.oldValue;

窗口关系及框架
如果页面中包含框架,则每个框架都有拥有自己的window对象,并且保存在frames和集合中,
在frames集合中,可以通过数值索引(从0开始,从左至右,从上到下)或者框架名称来访问相应的window对象。
每个window对象都有一个name属性,包含框架的名称。

<html>
      <head>
          <title>Frameset Example</title>
    </head>
    <framest  rows="160,*">
         <framest src="frame.htm"name="topFrame">
        <framest.color="50%,50%">
                   <frame src="anotherframe.htm" name="leftFrame">
                   <frame src="yetanotherframe.htm"name="rightFrame">
         </framest>
      </framest>
<html>
//以上代码创建了一个框架集,其中一个框架居上,两个框架居下
可以通过window,frame[0]或者window.frame["topFrame"]来引用上方框架

<html>
      <head>
          <title>Framest Example</title>
    </head>
    <frameset  rows="160,*">
         <frame src="frame.htm"name="topFrame">
        <frameset.color="50%,50%">
                   <frame src="anotherframe.htm" name="leftFrame">
                   <frame src="anotherframeset.htm"name="rightFrame">
         </frameset>
      </frameset>
<html>

<html>
   <head>
       <title>Frameset Example</title>
    </head>
      <frameset cols="50%,50%">
              <frame src="red.htm" name="redFrame">
            <frame src="blue.htm" name="blueFrame">
</frameset>
</html>

//浏览器在加载完第一个框架集之后,会继承将第二个框架集加载到rightFrame中。

self
self对象始终指向window,实际上,self和window对象可以互换使用

窗口位置
跨浏览器取得窗口左边和上边的位置
var leftPos=(typeof  window.screenLeft=="number")? window.screenLeft:window.screenX;
var  topPos=(typeof window.screenTop=="number")? window.screenTop:window.screenY;
//这个例子运用二元操作符首先确定screenLeft和screenTop属性是否存在,
如果是(在IE,Safari、Opera和Chrome中)、则取得这两个属性的值。
若不存在(在Firefox中),则取得screenX和screenY的值。
     
           
若window对象是最外层对象,且浏览器窗口紧贴窗口屏幕最上端——即y轴坐标为0,则screenTop的值是
位于页面可见区域上方的浏览器的浏览器工具栏的像素高度。但在Firefox和Safari中,screenY或screenTop
中保存的是整个浏览器窗口相对于屏幕的坐标值,即在窗口的y轴坐标为0时返回0.


moveTo()接受的是新位置的x和y坐标值,
moveBy()接受的是水平和垂直方向上移动的像素数
//将窗口移动到屏幕左上角
window.moveTo(0,0);

//将窗口向下移动100像素
window.moveBy(0,100);

//将窗口移动到(200,300)
window.moveBy(200,300);

//将窗口向左移动50像素
window.moveBy(-50,0);

窗口大小
innerWidth、innerHeight、outerWidth和outerHeright.
outerWidth、outerHeight返回窗口的本身的尺寸
innerWidth、innerHeight表示该容器中页面视图区的大小(j减去边框宽度)
在Chrome中,outerWidth、outerHeight与innerWidth、innerHeight返回相同的值(视口大小)


var pageWidth=window.innerWidth,
     pageHeight=window.innerHight;
if(typeof pageWidth!="number")//检查pageWidth中保存的是不是一个数值
{
   if(document.compatMode="CSS1Compat')//检查页面是否处于标准模式
{
     pageWidth=document.documentElement.clientWidth;//取得页面视口的信息
    pageHeight=document.documentElement.clientHeight;
}else//处于混杂模式下取得视口信息的方法
{
pageWidth=document.body.clientWidth;
pageHeight=document.body.clientHeight;
}
}
//取得页面视口的大小

//对于移动设备,window.innerWidth和window.innerHeight保存着可见视口,即屏幕可见页面区域的大小。

使用resizeTo()和resizeBy()方法可以调整浏览器窗口的大小
resizeTo()接受浏览器窗口的新宽度和新高度。resizeBy()接受新窗口与原窗口的宽度与高度之差

//调整到100*100
window.resizeTo(100,100);
//调整到200*150
window.resizeBy(100,50);
//调整到300*300
window.resizeTo(300,300);


导航和打开窗口
window.open()方法既可以导航到一个特定的URL,也可以打开一个新的浏览器窗口。
接受4个参数;要加载的布尔值,窗口目标,一个特性字符串以及一个表示新页面是否取代浏览器历史纪录中当前加载页面的布尔值
//等同于<a herf="http://www.wrox.com"target="topFrame"></a>
window.open("http://www.wrox.com/*,topFrame");


window.open("http://www.wrox.com/","wroxWindow","height=400,width=400,top=10,left=10,resizable=yes");
//打开一个新的可以调整大小的窗口,窗口初始大小为400*400像素,且距屏幕上沿和左边个10;
wroxWin.resizeTo(500,500);
//调整大小
wroxWin.moveTo(100,100);
//移动位置
调用close()方法还可以关闭新打开的窗口。
wroxWin.close();
弹出窗口屏蔽
若是浏览器内置的屏蔽程序阻止的弹出弹框
那么window.open()会返回null.
var wroxWin=window.open("http://www.wrox.com","_blank");
if(wroxWin==null){
   alert("The popup was blocked!");
}
否则,window.open会抛出一个错误。
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()方法,两个参数:要执行的代码和
以毫秒表示的时间
法一
setTimeout("alert("Hello word!")",1000);
法二
setTimeout(function(){
 alert("Hello world");
},1000;
//第二个参数表示一个等待多长时间的毫秒数,但经过改时间后指定的代码不一定会执行。
JS是一个单线程的解释器,因此一定时间只能执行一段代码。
如果JS的队列是空的,那么添加的代码会立即执行。如果
队列不是空的,那么它就要等前面的代码执行完了之后在执行。

setTimeout()被调用之后,该方法会返回一个数值ID,表示超时调用
//设置超时调用
var timeoutId=setTimeout(function(){
  alert("Hello world!");
},1000);
//注意,把他取消
clearTimeout(timeoutId);

setInterval(),方法进行间歇调用
法一
setInter("alert("Hello world!")",10000);
法二
setInterval(function(){
  alert("Hello world");
},10000);

ssetInterval()被调用之后,该方法会返回一个数值ID,表示间歇调用
var num=0;
var max=10;
var intervalId=null;
function incrementNumber(){
num++;
if(num=max){
  clearInterval(intervalId);
  alert("Dome");
}
}
intervalId=setInterval(incrementNumber,500);

上例中的模式也可以使用超时调用来实现
var num=0;
var max=10;
function incrementNumber(){
 num++;
//如果执行次数未达到max设置值,则设置另一次超时调用
if(num<max){
 setTimeout(incrementNumber,500);
}else{
 alert("Done");
}
}
setTimeout(incrementNumber,500);

系统对话框
alert()、confirm()、prompt()方法
if(confirm("Are you sure?")){
  alert("I'm so glad you're sure!");
}else{
 alert("I'm sorry to hear you're not sure.");
}
//在此例中第一行代码会显示一个对话框,
点击OK,显示I'm so glad you're sure!
点击Cancel;显示I'm sorry to hear you're not sure;


prompt()
//如果用户单击了Ok按钮,则prompt()返回文本输入域的值,否则,该方法返回null,

var result=prompt("What is your name?","");
if(result!==null){
 alert("Welcome."+result);
}

find()和print()方法
//显示“打印”对话框
window.print();
//显示“查找”对话框
window.find();


lacation对象

查询字符串参数
function getQueryStringArg(){
//取得查询字符串并去掉开头的问号
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=item.lengths;
//逐个将每一项添加到args对象中
for(i=0;i<len;i++){
 item=item[i].split("=");//根据等于号切割每一项
 name=decodeURLComponent(item[0]);//返回name
value=decodeURLComponent(item[1]);//返回value
if(name.length){
 args[name]=value;
}
}
return args;

//假设查询字符串是?q=javascript&num=10
var args=getQueryStringArg();
alert(args["q"]);//"javascript"
alert(args["num"]);//"10"
//可见,每个查询字符串参数都成了返回对象的属性,方便了对参数的访问

位置操作
使用location对象可以通过很多方式来改变浏览器的位置。
法一:使用assign()方法并为其传递一个URL
location.assign("http://www.wrox.com");
//打开新的URL并在浏览器的历史纪录中生成一个记录。
window.location="http://www.wrox.com"
location.herf="http://www.wrox.com"
//与使用assign()方法一样。


修改location对象的其他属性也可以改变当前加载的页面。
//假设初始化URL为http://www.wrox.com/WileyCDA/
//将URL修改为“http://www.wrox.com/WikeyCDA/#section1”
location.hash="#section";
//将URL修改为“http://www.wrox.com/WikeyCDA/?q=javascript”
location.search="?q=javascript";
//将URL修改为:http://www.yahoo.com/WileyCDA/"
location.hostname="www.yahoo.com";
//将URL修改为“http://www.yahoo.com/mydir/”
location.pathname="mydir";
//将URL修改为“http://www.yahoo.com:8080/WileyCDA/”
location.port=8080;
每次修改location的属性(hash除外),页面都会以新URL重新加载。

在调用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。
然后“后退”按钮将处于禁用状态。
reload()
 //reload()作用是重新加载当前页面
location.reload();//重新加载(有可能从缓存中加载)
location.reload(true);//重新加载(从服务器重新加载)
//位于reload()调用之后的代码也可能不会执行,最好将
reload()放在代码的最后一行。


navigator
//检测显示网页的浏览器类型

检测插件
//检测浏览器中是否安装了特定的插件是一种最常见的检测例程
//检测插件(在IE中无效)
function hasPlugin(name){
 name=name.toLowerCase();//将传入的名称转换为小写形式,以便于比较
 for(var i=0;i<navigator.pluging.length;i++){
 if(navigator.plugin[i].name.toLowerCase().indexOf(name)>-1)//通过indexOf()检测每个name属性,以确定传入的名称是否出现在字符串的某个地方
{
return true;
}
}
return false;
}
//检测Flash
alert(hasPlugin("Flash"));
//检测到QuickTime
alert(hasPlugin("QuickTime"));

IE是通过COM对象的方式实现插件的
COM对象使用唯一标识符来标识
Flash的标识符是ShockwaveFlash,ShockwaveFlash。
//检测IE中的插件
function hasIEPlugin(name){
try{
  new ActiveXObject(name);//接受一个COM标识符作为参数,在try-catch语句中进行实例化
 return true;
}catch(ex){
 return false;
}
}
//检测Flash
alert(hasIEPlugin("ShockwaveFlash,ShockwaveFlash"));
//检测QuickTime
alert(hasIEPlugin("QuickTime.QuickTime"));

//针对每个插件分别创建检测函数
//检测所有浏览器中的Flash
function hasFlash(){
 var result=hasPlugin("Flash");
if(!result){
 result=hasIEPlugin("ShockwaveFlash,ShockwaveFlash");
}
return result;
}
//检测所有浏览器中的QuickTime
function hasPlugin("QuickTime");
if(!result){
 result=hsaIEPlugin("QuicTime.QuickTime");
}
return result;
}
//检测Flash
alert(hasFlash());
//检测QuickTime
alert(hasQuickTime());

注册处理程序
navigator.registerConentHandler("application/rss+xml","http://www.somereader.com?feed=%s","Some Reader");
//第一个参数是RSS源的MIME类型。第二个参数是应该接受RSS源URL的URL,当下一次请求RSS源时,
浏览器就会打开指定的URL,


navigator.registerProtocolHander("mailto","http://www.somemailclient.com?cmd=%s","Some Mail Client");
//注册一个mailto协议的处理程序,该程序指向一个基于Web的电子邮件客户端。同样,第二个参数仍然是处理相应请求的URL

history对象

//后退一项
history.go(-1);
//前进一页
history.go(1);
//前进两页
history.go(2);
也可以给go()方法传递一个字符串参数,

//跳转到最近的wrox.com页面
history.go("wrox.com");

另 可以使用简写方法back()和forward()来代替go()
//后退和前进按钮
//后退一页
history.back();
//前进一页
history.forward();

if(history.length==0){
//这应该是用户打开窗口的第一个页面
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值