JavaScript--BOM對象

BOM(browser object model)瀏覽器對象模型

一、window對象

window是瀏覽器的一個實例,在瀏覽器中,window對象有雙重角色,它既是通過JavaScript訪問瀏覽器窗口的一個接口,又是ECMAScript規(guī)定的Global對象。

1.window對象的方法
①alert("content")
語法:window.alert(”content”)
功能:顯示帶有一段消息和一個確認按鈕的警告框

②confirm(“message")
語法:window.confirm(“message")
功能:顯示一個帶有指定消息和OK及取消按鈕的對話框
返回值:如果用戶點擊確定按鈕,則confirm()返回true
如果用戶點擊取消按鈕,則confirm()返回false

③prompt(“text,defaultText")
語法:window.prompt(“text,defaultText")
參數(shù)說明:
text:要在對話框中顯示的純文本(而不是HTML格式的文本)
defaultText:默認的輸入文本
返回值:如果用戶單擊提示框的取消按鈕,則返回null
如果用戶單擊確認按鈕,則返回輸入字段當前顯示的文本

注意:所有的全局變量和全局方法都被歸在window上

<body>
    <div id="box">
        <span>iphone6s</span>
        <input type="button" value="刪除" id="btn">
    </div>
    <script>
       var age=15;
       function sayAge(){
          alert('我'+window.age);
       }
       // 聲明一個全局變量
       window.username="marry";   // var username="marry";
       // 聲明一個全局方法
       window.sayName=function(){
          alert("我是"+this.username);
       }
       //sayAge();
       //window.sayName();

       // confirm()
       // 獲取按鈕,綁定事件
       var btn=document.getElementById("btn");
       btn.onclick=function(){
           // 彈出確認對話框
           var result=window.confirm("您確定要刪除嗎?刪除之后該信息\n將不可恢復!");
           if(result){
              document.getElementById("box").style.display="none";
           }
       }
       // 彈出輸入框
       //var message=prompt("請輸入您的星座","天蝎座");
       //console.log(message);
    </script>
</body>
全局變量
全局函數(shù)

④open(pageURL,name,parameters)
語法:window.open(pageURL,name,parameters)
功能:打開一個新的瀏覽器窗口或查找一個已命名的窗口
參數(shù)說明:
pageURL:子窗口路徑
name:子窗口句柄。(name聲明了新窗口的名稱,方便后期通過name對子窗口進行引用)
parameters :窗口參數(shù)(各參數(shù)用逗號分隔)

⑤close( )
語法:window.close( )
功能:關閉瀏覽器窗口

index1.html:

<head>
    <meta charset="UTF-8">
    <title>open</title>
</head>
<body>
    <input type="button" value="退 出" id="quit">
    <script>
       window.onload = function(){
          // 打開子窗口,顯示newwindow.html
          window.open("newwindow.html","newwindow","width=400,height=200,left=0,top=0,toolbar=no,menubar=no,scrollbars=no,location=no,status=no");
          //name的作用:在引用子窗口的時候通過name引用
          var quit = document.getElementById("quit");
          // 點擊關閉當前窗口
          quit.onclick = function(){
              window.close();
          }
       }
    </script>
</body>

newwindow.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>hello window.open</h1>
</body>
</html>
設置窗口屬性

⑥定時器

JavaScript是單線程語言,單線程就是所執(zhí)行的代碼必須按照順序。

超時調用:
語法:setTimeout(code,millisec)
功能:在指定的毫秒數(shù)后調用函數(shù)或計算表達式
參數(shù)說明:
1、code:要調用的函數(shù)或要執(zhí)行的JavaScript代碼串
2、millisec:在執(zhí)行代碼前需等待的毫秒數(shù)

說明:setTimeout()只執(zhí)行code一次。如果要多次調用,請使用setInterval()或者讓code自身再次調用setTimeout()

setTimeout方法返回一個ID值,通過它取消超時調用

清除超時調用:
語法:clearTimeout(id_of_settimeout)
功能:取消由setTimeout()方法設置的timeout
參數(shù)說明:
1、 id_of_settimeout :由setTimeout()返回的ID值,該值標識要取消的延遲執(zhí)行代碼塊

<body>
    <script>
       //setTimeout("alert('hello')",4000);
       
       //匿名函數(shù)
       var timeout1=setTimeout(function(){
          alert("hello");
       },2000)

       //自定義函數(shù)
       var fnCall=function(){
          alert("world");
       }
       clearTimeout(timeout1);
        //推薦:
       //setTimeout(fnCall,5000);
    </script>
</body>

間歇調用:
語法:setInterval(code,millisec)
功能:每隔指定的時間執(zhí)行一次代碼
參數(shù)說明:
1、code:要調用的函數(shù)或要執(zhí)行的代碼串。
2、millisec:周期性執(zhí)行或調用code之間的時間間隔,以毫秒計

<body>
    <script>
       /* var intervalId=setInterval(function(){
           console.log("您好");
        },1000)

        // 10秒之后停止打印
        setTimeout(function(){
            clearInterval(intervalId);
        },10000);*/
        
        var num=1,
            max=10,
            timer=null;
       
       // 每隔1秒針num遞增一次,直到num的值等于max,清除定時器
      /* timer=setInterval(function(){
           console.log(num);
           num++;
           if(num>max){
              clearInterval(timer);
           }
       },1000)*/

       // 使用超時調用實現(xiàn)
       function inCreamentNum(){
           console.log(num);   // 1 2 3 10 
           num++;      
           if(num<=max){
              setTimeout(inCreamentNum,1000);
           }else{
              clearTimeout(timer);
           }
       }
       timer=setTimeout(inCreamentNum,1000);
    </script>
</body>

二、location對象

location對象提供了與當前窗口中加載的文檔有關的信息,還提供了一些導航的功能,它既是window對象的屬性,也是document對象的屬性。

1.location對象的常用屬性
①location.href
語法:location.href
功能:返回當前加載頁面的完整URL
說明: location.href與window.location.href等價

②語法:location.hash
功能:返回URL中的hash(#號后 跟零或多個字符),如果不包含
則返回空字符串。

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
       .box1{height:400px;background:#ccc;}
       .box2{height:600px;background:#666;}
    </style>
</head>
<body>
    <div class="box1" id="top"></div>
    <div class="box2"></div>
    <input type="button" id="btn" value="返回頂部">
    <script>
       //console.log(location.href);
       //file:///E:/BaiduNetdiskDownload/JavaScript/js%E8%B5%84%E6%96%99%E5%92%8C%E6…E5%9F%BA%E7%A1%80%EF%BC%88%E6%BA%90%E4%BB%A3%E7%A0%81%EF%BC%89/index6.html
       //console.log(location.hash); 
       //在連接中加入錨點 打印錨點#top
       var btn=document.getElementById("btn");
       btn.onclick=function(){
          location.hash="#top";
       }
       console.log(location.pathname);
    </script>
</body>

③location.host
語法:location.host
功能:返回服務器名稱和端口號(如果有)

④location.hostname
語法:location.hostname
功能:返回不帶端口號的服務器名稱。

⑤location.pathname
語法:location.pathname
功能:返回URL中的目錄和(或)文件名。

⑥location.port
語法:location.port
功能:返回URL中指定的端口號,如果沒有,返回空字符串。

⑦location.protocol
語法:location.protocol
功能:返回頁面使用的協(xié)議。

⑧l(xiāng)ocation.search
語法:location.search
功能:返回URL的查詢字符串。這個字符串以問號開頭。

xxxx?id=55&name=marry;
location.search;
"?id=55&name=marry;"

2.locating對象的位置操作
改變?yōu)g覽器位置的方法:
location.href屬性
location對象其他屬性也可改變URL:
location.hash
location.search

①location.replace()
語法:location.replace(url)
功能:重新定向URL。
說明: 使用location.replace不會在歷史記錄中生成新紀錄。

②location.reload()
語法:location.reload()
功能:重新加載當前顯示的頁面。
說明:
? location.reload()有可能從緩存中加載
? location.reload(true)從服務器重新加載

<body>
    <input type="button" value="刷新" id="reload">
    <script>
      /*  setTimeout(function(){
            //location.href='index6.html';
            // window.location='index6.html';
            location.replace("index6.html");
        },1000)*/
         document.getElementById("reload").onclick=function(){
             location.reload(true);
         }
    </script>
</body>

三、history對象

history對象保存了用戶在瀏覽器中訪問頁面的歷史記錄

①history.back()
語法:history.back()
功能:回到歷史記錄的上一步
說明:相當于使用了history.go(-1)

②history.forward()
語法:location.forward()
功能:回到歷史記錄的下一步
說明:相當于使用了history.go(1)

③history.go(-n)
語法:history.go(-n)
功能:回到歷史記錄的前n步

④history.go(n)
語法:history.go(n)
功能:回到歷史記錄的后n步

<body>
    <p>這是index11.html</p>
    <p><input type="button" value="后退" id="btn"></p>
    <p><input type="button" value="前進" id="btn2"></p>
    <p><input type="button" value="前進兩步" id="btn3"></p>
    <script>
        var btn=document.getElementById("btn");
        var btn2=document.getElementById("btn2");
        var btn3=document.getElementById("btn3");
        //點擊btn按鈕時回到歷史記錄的上一步
        btn.onclick=function(){
            //history.back();
            //history.go(-1);
            history.go(-2);//回到前兩步
        }
        //點擊btn2按鈕來到歷史記錄的下一步
        btn2.onclick=function(){        
            //history.forward();
            history.go(1);
        }
        //點擊btn3按鈕來到歷史記錄的下一步
        btn3.onclick=function(){        
            history.go(2);
        }
    </script>
</body>

四、Screen對象

包含有關客戶端顯示屏幕的信息
①screen.availWidth
語法:screen.availWidth
功能:返回可用的屏幕寬度

②screen.availHeight
語法:screen.availHeight
功能:返回可用的屏幕高度

<body>
    <script>
        //獲取屏幕的寬和高
        console.log("頁面寬:"+screen.availWidth);
        console.log("頁面高:"+screen.availHeight);
        //獲取窗口的寬和高
        console.log("pageWidth:"+window.innerWidth);
        console.log("pageHeight:"+window.innerHeight);
    </script>
</body>

五、Navigator對象

UserAgent:用來識別瀏覽器名稱、版本、引擎 以及操作系統(tǒng)等信息的內容。
可以判斷瀏覽器的類型
判斷設備的終端是移動還是PC

<head>
    <meta charset="UTF-8">
    <title>Navigator</title>
</head>
<body>
    <script>
       //console.log(navigator.userAgent);
       // 判斷瀏覽器
       function getBrowser(){
           var explorer = navigator.userAgent,browser;
           //indexOf():返回某個指定的字符串值在字符串中首次出現(xiàn)的位置,如果沒有出現(xiàn)過,返回-1
           if(explorer.indexOf("MSIE")>-1){
              browser = "IE";
           }else if(explorer.indexOf("Chrome")>-1){
              browser = "Chrome";
           }else if(explorer.indexOf("Opera")>-1){
              browser = "Opera";
           }else if(explorer.indexOf("Safari")>-1){
              browser = "Safari";
           }
           return browser;
       }
       var browser = getBrowser();
       console.log("您當前使用的瀏覽器是:"+browser);
       // 判斷終端
       function isPc(){
          var userAgentInfo = navigator.userAgent,
              Agents = ["Andriod","iPhone","symbianOS","windows phone","iPad","iPod"],
              flag = true,i;
              console.log(userAgentInfo);
           for(i=0;i<Agents.length;i++){
              if(userAgentInfo.indexOf(Agents[i])>-1){
                 flag = false;
                 break;
              }
           }
           return flag;
       }
       var isPcs = isPc();
       console.log(isPcs);
    </script>
</body>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容