BOM

来源:互联网 发布:京东金融 免费数据 编辑:程序博客网 时间:2024/05/24 03:54

window对象

  • 窗口位置
    1.表示窗口相对于屏幕左边和右边的位置:screenLeft 、screenTop 、screenX、screenY(IE/Safari/Opera/Chrome)
    screenX、screenY(Firefox/Safari/Chrome/Opera中代表不同的意义)
    跨浏览器写法:
var leftPos = (typeof window.screenLeft = "number") ? window.screenLeft : window.screenX;var topPos = (type of window.screenTop = "number") ? window.screenTop : window.screenX
  • 窗口大小
    确定浏览器窗口大小:innerWidth、innerHeight、outerWidth、outerHeigh.
    outerWidth、outerHeigh(IE9+/Safari/Firefox):返回浏览器窗口本身的尺寸
    innerWidth、innerHeight、outerWidth、outerHeigh(出肉):返回相同的值,即视口大小

虽然最终无法确定窗口大小,但可以取得页面视口的大小,取得视口大小的兼容性写法

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;        }    }
  • 导航和打开窗口
window.open("http://www.baidu.com/","height = 400,width =200,top = 10, left = 10")

location对象

提供与当前窗口中加载的文档有关的信息,还提供了一些导航功能。window.logcation和document.location提供的是同一个对象

属性名 例子 说明 hash “#contents” 返回URL中的hash host “www.wrox.com:80” 返回服务器名称和端口号 hostname “www.wrox.com” 返回不带端口号的服务器名称 href “http:/www.wrox.com” 返回当前加载页面的完整URL,location对象的toString()方法也返回这个值 pathname “/wiley” 返回URL中的目录或文件名 *port “8080” 返回URL中指定的端口号 protocol “http:” 返回页面使用的协议,通常是http:或https: search “?q=javascript&p=html” 返回URL的查询字符串,这个字符串以问号开头
  • 查询字符串参数
function getQueryString(){    var query = location.search.length>0?location.search.substring(1):"";    var result = {};    query.split("&").forEach(function(port){        var item = port.split("=");        result[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);    })    return result}

比如网页的URL为https://www.google.com/search?new=1&safe=strict
1.函数的第一步是先去掉查询字符串的问号,得到”new=1&safe=stric”
2.函数的第二步将查询字符串中间的&去掉,并返回一个字符串数组[“new=1”,”safe=2],然后对数组进行迭代操作
3.根据等于号分割每一项,返回第一项为参数名,第二项为参数值的数(第一项和第二项要分别进行解码,因为查询字符串应该是被编码过的),说到这里,可以关注一下decodeURIComponent和decodeURI的区别

函数的示例

var args = getQueryString();console.log(args[new]);//1console.log(args[safe]);//2

history对象

history对象保存着用户上网的历史记录
使用go()方法可以在用户的历史记录中跳转,可以向前也可以向后

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

这两个按钮也可以模仿浏览器的前进后退按钮

history.back();//后退一页history.forword();//前进一页
原创粉丝点击