BOM的常见方法和内置对象

弹出系统对话框:

alert();    //不同浏览器中alert弹出框的外观是不同的
confirm();  //缺点: 兼容不太好
prompt();   //不推荐使用

打开窗口, 关闭窗口:

window.open(url,target)
  • 参数解释:
    • url: 要打开的地址.
    • target: 新窗口的地址. 可以是: _blank_self_parent父框架.
  • 代码示例:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<!--行间的js中的open() window不能省略-->
<button onclick="window.open('https://www.luffycity.com/')">路飞学城</button>

<button>打开百度</button>
<button onclick="window.close()">关闭</button>
<button>关闭</button>

</body>
<script type="text/javascript">

    var oBtn = document.getElementsByTagName('button')[1];
    var closeBtn = document.getElementsByTagName('button')[3];

    oBtn.onclick = function(){
    //open('https://www.baidu.com')
    //打开空白页面
    open('about:blank',"_self")
    }
    closeBtn.onclick = function(){
        if(confirm("是否关闭?")){
            close();
        }
    }

</script>
</html>

location对象的属性:

  • href: 跳转.
  • hash: 返回url中#后面的内容, 包含#.
  • host: 主机名, 包括端口.
  • hostname: 主机名.
  • pathname: url中的路径部分.
  • protocol: 协议 一般是http, https.
  • search: 查询字符串.

location.href属性举例:

  • 举例1: 点击盒子时, 进行跳转.
<body>
<div>smyhvae</div>
<script>
    var div = document.getElementsByTagName("div")[0];

    div.onclick = function () {
        location.href = "http://www.baidu.com";   //点击div时,跳转到指定链接
        //window.open("http://www.baidu.com","_blank");  //方式二
    }
</script>
</body>
  • 举例2: 5秒后自动跳转到百度.
<script>
    setTimeout(function () {
        location.href = "http://www.baidu.com";
    }, 5000);
</script>

location对象的方法:

  • location.reload(): 重新加载
setTimeout(function(){
    //3秒之后让网页整个刷新
    window.location.reload();      
},3000)

navigator对象:

window.navigator 的一些属性可以获取客户端的一些信息.

  • userAgent:系统,浏览器
  • platform:浏览器支持的系统,win/mac/linux
console.log(navigator.userAgent);
console.log(navigator.platform);

history对象:

  • 后退:
    • history.back()
    • history.go(-1):0是刷新
  • 前进:
    • history.forward()
    • history.go(1)
原文地址:https://www.cnblogs.com/login123/p/12243442.html