读javascript高级程序设计09-BOM

王朝学院·作者佚名  2016-05-23
窄屏简体版  字體: 小  |  中  |  大  |  超大  

读javascript高级程序设计09-BOM一、window1.在全局作用域中定义的变量和函数会被归在window对象。

var a=1,b=2;function add(a,b){return a+b;}console.log(window.a);//1console.log(window.add(a,b));//3

有点区别在于,全局变量不能用delete删除,而直接在window对象定义的属性可以用delete删除。

2.计算窗口位置:

var leftpos=typeof window.screenLeft=="number"?window.screenLeft:window.screenX;var toppos=typeof window.screenTop=="number"?window.screenTop:window.screenY;

3.间接性调用:

①setInterval方法:

var i=1,max=10; function f(){ if(i==max){ clearInterval(test); console.log('Done'); } else{ console.log(i); i++; } }var test=setInterval(f,1000);

②用setTimeout方法实现:

var i=1,max=10; function f(){ if(i==max){ console.log('Done'); } else{ console.log(i); setTimeout(f,1000); i++; } }var test=setTimeout(f,1000);

使用超时调用模拟间歇调用是一种最佳实践。

4.系统对话框

PRompt:

var result=prompt("your name?");if(result!=null){alert('hello,'+result);}

二、location对象1.location对象属性:

window.location和document.location指向同一个对象。

每次修改location的属性(hash除外),都会以新URL重新加载页面。

location对象几个常用的属性实例:

//url为:http://www.cnblogs.com/janes/p/3829648.html//hash:用于锚点定位location.hash="#author_profile_info";//定位到头像//hostname:不带端口号的服务器名称location.hostname;//"www.cnblogs.com"//href:当前页面的完整urllocation.href;//"http://www.cnblogs.com/janes/p/3829648.html#author_profile_info"//pathname:url中的路径名或者文件名location.pathname;//"/janes/p/3829648.html"//search:url中的查询字符串,以问号开头location.search;//""

2. 获取查询字符串参数:

function getQueryArgs(){ var qs=location.search.length>0?location.search.substring(1):""; var result={}; var items=qs.length?qs.split('&'):[]; var item=null,name=null,value=null; for(var i=0;i<items.length;i++){ item=items[i].split('='); name=decodeURIComponent(item[0]); value=decodeURIComponent(item[1]); if(name.length>0){ result[name]=value; } } return result;}var r=getQueryArgs();

3.修改url:

location.href="http://www.baidu.com";//打开新URL之后可以通过浏览器后退回到前一页面location.replace("http://www.baidu.com");//打开新URL之后在某些浏览器下不能通过后退回到前一页面

重新加载页面:

location.reload():可能从缓存加载location.reload(true):重新从服务器加载

三、navigator对象1.常用属性

navigator.cookieEnabled:浏览器cookie是否可用navigator.userAgent:浏览器的用户代理字符串;

2.检测插件:检测浏览器中是否安装了某个插件。

非IE浏览器:使用plugins数组,判断插件名称在name属性中是否存在。

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;}//调用hasPlugin('Flash');

IE浏览器:使用ActiveObject对象,并尝试创建插件的一个实例。

function hasIePlugin(name) { try { new ActiveXObject(name); return true; } catch(ex) { return false; }}//调用hasIePlugin('ShockWaveFlash.ShockWaveFlash');

由于两种检测方式差异较大,所以一般针对每个插件写单独的检测方法:

function hasFlash() { var result = hasPlugin('flash'); if (!result) { result = hasIePlugin('ShockWaveFlash.ShockWaveFlash'); } return result;}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航