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

BOM 浏览器对象模型

2017-04-05 00:00 274 查看
这里详细说一下令我头痛的window对象:BOM的核心对象

window位置:

IE、Safari、Opera、Chrome提供了screenLeft、screenTop表示窗口相对于屏幕左边和上边的位置;Firefox使用screenX和screenY,但与screenLeft和screenTop并不对应

取得窗口左边和上边的位置:

let leftPos = (typeof window.screenLeft === 'number') ? window.screenLeft : window.screenX
let topPos = (typeof window.screenTop === 'number') ? window.screenTop : window.screenY

有两个方法可以移动window

// 窗口移动到屏幕左上角
window.moveTo(0, 0);

// 窗口乡下移动100px
window.moveBy(0, 100)


window大小:innerWidth, innerHeight, outerWidth, outerHeight

取得页面视口大小:

let pageWidth = window.innerWidth,
pageHeight = window.innerHeight;
if (typeof pageWidth !== 'number') {
if (document.compactMode === 'CSS1Compact') {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}

}


打开页面:window.open('http://www.baidu.com', 'topFrame')

间歇调用和超时调用

每半秒num + 1, 直到10 (目测需要5s)

var num = 0;
var max = 10;
var intervalId = null;

function incrementNumber () {
num++;
if (num === max) {
clearInterval(intervalId);
alert('Done');
}
}

intervalId = setInterval(incrementNumber, 500);

使用超时调用实现上面的功能

var num = 0;
var max = 10;
var intervalId = null;

// 递归调用
function incrementNumber () {
num++;
if (num < max) {
setTimeout(incrementNumber, 500);
} else {
alert('Done');
}
}

setTimeout(incrementNumber, 500);

建议使用超时调用,因为后一个间歇调用会在前一个间歇调用结束之前启动

location对象:最有用的BOM对象之一



获取查询字串对象

function getQueryStringArgs () {
// 取得查询字符串并去掉开头的问号
var qs = (location.search.length > 0 ? location.search.substring(1) : ''),
args = {},
// 取得每一项
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
i = 0,
len = items.length;

// 在for循环中使用
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;
}


位置操作

下面三个方式效果是一样的,立即打开新的url,并且在浏览记录中生成一条记录

location.assign('//cn.bing.com')
location = '//cn.bing.com'
location.href = 'cn.bing.com'

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

只要修改了location的属性(包括hash) 浏览器的历史记录都会生成一条新记录

如果不想生成新的历史记录,可以调用replace(),会用新的url替换浏览器历史记录中当前显示的页面

reload()方法

location.reload(); //重新加载 (有可能从缓存中加载)
location.reload(true); // 重新(从服务器重新加载)


navigator对象





检测浏览器安装了哪些插件:

navigator.plugins




screen对象





常用是width、height属性

history对象

保存着用户上网的历史记录

history.go(-1); // 后退一页
history.go(1); // 前进一页
history.go(2); // 前进两页

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

history.back(); // 后退一页
history.forward(); // 前进一页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js BOM Window