天天看點

JavaScript - BOM 浏覽器對象模型

 浏覽器對象模型(Browser Object Model) 允許JavaScript與浏覽器對話

Window對象: 

  1. 所有浏覽器都支援window對象,它代表浏覽器的視窗  
  2. 全局變量是window對象的屬性
  3. 全局函數是window對象的方法
  4. 甚至(HTML DOM)的 document對象也是 window 對象屬性 

視窗尺寸:

         window.innerHeigth --浏覽器視窗的内高度

         window.innerWidth--浏覽器視窗的内寬度

但是有些浏覽器的版本不支援這兩種方法,他們用的是: 

         document.documentElement.clientHeight

         document.documentElement.clientWidth    

或:

           document.body.clientHeigth 

          document.body.clientWidth

有一個可以包括所有浏覽器的解決方法: 

執行個體:

var w =window.innerWidth || document.documentElement.clientWidth||document.body.clientWidht

var h=window.innerheight||document.documentElement.clientHeight||document.body.clientHeight
           

window對象-計時器對象:

文法:
 ->  開啟計時器: 
    number window.setInterval(callback,millisecond);

 ->  關閉計時器:
    window.clearInterval(intervalId);

           

  案例:

<script type="text/javaScript">
    onload=function(){
    window.date.innerHTML=new Date().tolocaleString();
    setInterval(function(){

    window.date.innerHTML=new Date().toLocaleString();},1000);
}; 
</script>
           

 window對象-延時器:

文法:  

開啟: number window.setTimeout(callback,millisecond);
等待指定時間調用回調函數,隻會執行一次,傳回的是示範器id

關閉: clearTimeout(timeoutId);
           

window對象-剪貼闆:

文法:
設定值:  -> clipboardData.seData("text",值);
取值: -> clipboardData.getData("text",值);
           

 案例:

<script>
    onload=function(){
    document.getElementById("btn").onClick=function(){
    var rul=location.href;
    //放入剪切闆:
    window.clipboardData.setData("text",url);
//得到剪切闆的内容
document.getElementById("btn1").onClick=function(){
    var txt=window.clipboardData.getData("text");
}
};
};
</script>



  
           

confirm 方法:

  用于顯示一個帶有指定消息以及按鈕的對話框

<script type="text/javascript">
        onload = function () {
            btn.onclick = function () {
                var res = window.confirm("測試消息,請選擇");
                alert(res);
            };
        };

    </script>
</head>
<body>
    <input type="button" name="name" value="click" id="btn"/>
</body>

結果:當點選确定的時候,顯示true,取消的時候顯示false
           

location對象:

  •  作用:頁面跳轉
<script type="text/javascript">
        onload = function () {
            btn.onclick = function () {
                window.location.href = "https://www.baidu.com/";
            };
        };
    </script>
           

screen對象

  • screen.width :屬性傳回以像素的螢幕寬度
例子: 

document.getElementById("demo").innerHTML=screen.width;
           
  • screen.height:傳回螢幕的高度

 location對象: 可以不加window字首

location.href

傳回目前頁面的href

document.getElementById("demo").innerHTML="目前頁面是"+window.location.href;

location.hostname 傳回目前web主機的域名
location.pathname 傳回目前頁面的路徑或檔案名
location.protocol 傳回使用的web協定
location.assign 加載新文檔

history對象:

   包含浏覽器曆史

  •    history.back() 方法加載曆史清單中的前一個URL;

   等價于在浏覽器中點選後退按鈕

  •     histroy.forward() 加載曆史清單中的下一個URL;

繼續閱讀