您的位置:首页 > Web前端 > JavaScript

读javascript高级程序设计09-BOM

2014-08-01 15:54 337 查看

一、window

1.在全局作用域中定义的变量和函数会被归在window对象。

var a=1,b=2;
function add(a,b){
return a+b;
}
console.log(window.a);//1
console.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:当前页面的完整url
location.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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: