Javascript操作DOM對象

一、BOM模型

  • BOM:瀏覽器對象模型(Browser Object Model)
    • BOM提供了獨立于內(nèi)容的、可以與瀏覽器窗口進行互動的對象結(jié)構(gòu)
BOM可實現(xiàn)功能
  • 彈出新的瀏覽器窗口

  • 移動、關(guān)閉瀏覽器窗口及調(diào)整窗口的大小

  • 頁面的前進、后退

    二、window對象

? 在客戶端JavaScript中,Window對象是全局對象,所有的表達式都在當(dāng)前的環(huán)境中計算

1.常用的屬性
屬性名稱 說明
history 有關(guān)客戶訪問過的URL信息
location 有關(guān)當(dāng)前URL的信息
//語法
window.屬性名="屬性值"
//示例
window.location="http://www.ss-vet.com";//表示跳轉(zhuǎn)道盛邦升華首頁
2.常用的方法
方法名稱 說明
prompt() 顯示可提示用戶輸入的對話框
alert() 顯示帶有一個提示信息和一個確定按鈕的警示框
confirm() 顯示一個帶有提示信息、確定和取消按鈕的對話框
close() 關(guān)閉瀏覽器窗口
open() 打開一個新的瀏覽器窗口,加載給定URL所指定的文檔
setTimeout() 在指定的毫秒數(shù)后調(diào)用函數(shù)或計算表達式
setInterval() 按照指定的周期(以毫秒計)來調(diào)用函數(shù)或表達式
2.1 confirm()方法

? 瀏覽器可以通過調(diào)用系統(tǒng)對話框,向用戶顯示信息。系統(tǒng)提供了3個函數(shù),可以完成系統(tǒng)對話框操作。分別是alert() prompt() confirm().

【注意】window下的函數(shù),都可以省略window直接去調(diào)用

confirm() 將彈出一個確認對話框

語法:confirm("對話框中顯示的純文本")

<script type="text/javascript">
   var flag=confirm("確認要刪除此條信息嗎?");
    if(flag==true){
          alert("刪除成功!");
    } else{
           alert("你取消了刪除");
    }
</script>
confirm()與alert ()、 prompt()區(qū)別
    1.alert( ):警告框。一個參數(shù),僅顯示警告對話框的消息,無返回值,不能對腳本產(chǎn)生任何改變
    2.prompt( ):提示框。兩個參數(shù),輸入對話框,用來提示用戶輸入一些信息,單擊“取消”按鈕則返回null,單擊“確定”按鈕則返回用戶輸入的值,常用于收集用戶關(guān)于特定問題而反饋的信息
     【參數(shù)】第一個參數(shù):要在提示框上顯示的內(nèi)容;第二個參數(shù):輸入框內(nèi)默認的值
    3.confirm( ):確認對話框。一個參數(shù),確認對話框,顯示提示對話框的消息、“確定”按鈕和“取消”按鈕,單擊“確定”按鈕返回true,單擊“取消”按鈕返回false,因此與if-else語句搭配使用

2.2open()方法

打開一個新窗口

window.open() 等價于 open()

語法:window.open("彈出窗口的url","窗口名稱","窗口特征”)

參數(shù)詳情: 1.要加載URL 2.窗口的名稱或窗口的目標(biāo) 3.一串具有特殊意義的字符串

案例:點擊按鈕,彈出頁面
<input type="button" value="按鈕" id="btn">
<script>
    var oBtn=document.getElementById("btn");
    oBtn.onclick=function(){
   open("http://www.baidu.com");
        /*  
        【注意】如果只有第一個參數(shù),調(diào)用open方法會打開新窗口,加載url
         */
    open("http://www.baidu.com","百度");      
        /* 
        【注意】第二個參數(shù),是給打開的新窗口起一個名字,以后再去加載url,就在
                 這個已經(jīng)起好名字的目標(biāo)窗口加載url
        */
    open("http://www.baidu.com","百度","width=400,height=400,top=200,left=200");
            /*
            【注意】第三個參數(shù),是給打開的新窗口起一個名字,以后再去加載url,就在
            這個已經(jīng)起好名字的目標(biāo)窗口加載url
         */
            }       
</script>    
練習(xí)1需求:有兩個頁面,父頁面sup.html設(shè)置黃色,子頁面sub.html設(shè)置紫色。
        父窗口點擊按鈕跳轉(zhuǎn)到子頁面,子頁面點擊按鈕打開父窗口      
//父窗口
<html>
    <head>
        <meta charset="utf-8">
        <title>父窗口</title>
        <style type="text/css">
            body{
                background: #FFFF00;
            }
        </style>
    </head>
    <body>
        <input type="button" value="打開子窗口" id="btn">
        <script>
            var oBtn=document.getElementById("btn");
            oBtn.onclick=function(){
                open("sub.html","子窗口","width=400,height=400,top=200,left=200")
            }
        </script>
    </body>
</html>
//子窗口
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            body{
                background: blueviolet;
            }
        </style>
    </head>
    <body>
        <input type="button" value="按鈕" id="btn">
        <script>
            /* opener:打開當(dāng)前窗口的父窗口的window對象
                注意:IE不支持該對象
             */
            var oBtn=document.getElementById("btn");
            oBtn.onclick=function(){
                alert(opener); //window object  不確定是不是父級,用下行代碼測試
                opener.document.write("子窗口讓我輸出的");
            }
        </script>
    </body>
</html>

三、history對象

? history是window對象的屬性,它保存這個用戶上網(wǎng)的記錄。

1.history屬性(了解)

history.length 返回當(dāng)前history對象中記錄數(shù):歷史記錄條數(shù)

//html
<input type="button" value="記錄" id="btn">
    
//js
 var oBtn=document.getElementById("btn");
    oBtn.onclick=function(){
    alert(history.length);
}
/* 
    手動在鏈接后添加 #1按回車 #2按回車 #3按回車
    再點擊記錄按鈕,會發(fā)現(xiàn)展示四條記錄
*/

2.history屬性(重點)

名稱 說明
back() 加載history對象列表中的前一個url
forward() 加載history對象列表中的下一個url
go() 加載history對象列表中的某個具體url
 history方法
    history.back() 返回上一條歷史記錄,類似于后退
    history.forward() 前進到下一條歷史記錄,類似前進
    history.go()
        參數(shù)  0     重載當(dāng)前頁面
            正數(shù)    前進對應(yīng)數(shù)量的記錄
            負數(shù)    后退對應(yīng)數(shù)量的記錄
*/
//html:創(chuàng)建3個按鈕
<input type="button" value="前進" id="forward">
<input type="button" value="后退" id="back">
<input type="button" value="go" id="go">
    
//js:控制url前進還是后退 
var oBtn1=document.getElementById("forward");
oBtn1.onclick=function(){
    history.forward();
}
            
var oBtn2=document.getElementById("btn");
oBtn2.onclick=function(){
    history.back();
}
            
var oBtn3=document.getElementById("btn");
oBtn3.onclick=function(){
    history.go(0);
    history.go(2);
    history.go(-2);
}

四、location對象

? location是BOM對象之一,它提供了與當(dāng)前窗口中加載的文檔有關(guān)的信息,還提供了一些導(dǎo)航功能。事實上,location對象是window對象的屬性,也是document對象的屬性;所以window.loction和document.location等效。

  • alert(window.location); //獲取當(dāng)前的URL

  • alert(location); //window可以省略

  • alert(window.document.location);

    可以看出以上三種方式彈出結(jié)果相等。alert(window.location===window.document.location);//true

//案例1:查看location結(jié)果
alert(window.location);
alert(location);
alert(window.document.location);
alert(window.location===window.document.location);//true
**location 我們?yōu)g覽器上的地址欄輸入框**

1.常用屬性

名稱 說明
host 設(shè)置或返回主機名和當(dāng)前URL的端口號
hostname 設(shè)置返回當(dāng)前URL的主機名
href 設(shè)置和返回完整的URL
/* 
location 中屬性
    url:統(tǒng)一資源定位符(快遞包上一個地址)
    1.location.hash 錨點 #1 實現(xiàn)頁面內(nèi)跳轉(zhuǎn)
*/
alert(location.hash);
 window.onload=function(){
 document.onclick=function(){
     location.hash="#1";
 }
}
/*
2.host 主機名:端口號  瀏覽器的端口號默認 8080
    IP 通過IP我們可以在全球范圍內(nèi),找到我這臺電腦所使用的網(wǎng)絡(luò)的端口號 
    正在使用網(wǎng)絡(luò)的軟件,在當(dāng)前電腦內(nèi)唯一的標(biāo)識。
    IP:端口號
*/
 /* 
3.hostname 主機名 域名/IP
    【注意】域名其實就是給IP起一個好記的名字
 */
alert(location.hostname); //需要將此頁面部署到服務(wù)器上
/* 
4.href 整個url
*/
alert(location.href);
/* 
5.pathname 路徑名
 */
alert(location.pathname);
        
/* 
 6.protocal 協(xié)議
http:網(wǎng)絡(luò)協(xié)議
 file:本地文件協(xié)議
*/
alert(location.protocol);
/* 
7.search 查詢字符串
    跟在?后面的部分
    ?username=XXX&age=18
 */ 
alert(location.search);
window.onload=function(){
    document.onclick=function(){
        location.search="?xxx=yyy&age=18";
    }
}
/* 
url統(tǒng)一資源定位符
    protocol(協(xié)議):host(主機名):port(端口號)/pathname(路徑)?username=xxx&age=18#1
 */

2.常用方法

名稱 說明
reload 重新加載當(dāng)前文檔
replace 新的文檔替換當(dāng)前文檔
assign 跳轉(zhuǎn)到指定的URL
/* 
assign() 跳轉(zhuǎn)到指定的url 
reload()重載當(dāng)前的url
        如果傳參,參數(shù)為true的時候,強制加載,從服務(wù)器源頭重新加載
replace() 用新的url替換當(dāng)前頁面,可以避免跳轉(zhuǎn)前的歷史記錄
            
*/
var oBtn=document.getElementById("btn");
oBtn.onclick=function(){
    location.assign("http://www.baidu.com");
        //location.reload(); //緩存
        //location.reload(true);
    location.replace("http://www.baidu.com");
}

五、Document對象

常用屬性

名稱 說明
referrer 返回載入當(dāng)前文檔的URL
URL 返回當(dāng)前文檔的URL
//語法:
doctument.referrer
document.URL

案例:判斷頁面來源并跳轉(zhuǎn)(3個頁面)

//1.html頁面
<style type="text/css">
     body,h1{margin: 0;padding: 0;}
      .prize{text-align: center;}
</style>
<div class="prize">
    <img src="images/d1.jpg" alt="中獎" />
    <h1><a href="praise.html">馬上去領(lǐng)獎啦!</a></h1>
</div>
//2.praise頁面
//判斷頁面是否是鏈接進入
//自動跳轉(zhuǎn)到登錄頁面
<script type="text/javascript">
    var preUrl=document.referrer;  //載入本頁面文檔的地址
    if(preUrl==""){
        document.write("<h2>您不是從領(lǐng)獎頁面進入,5秒后將自動跳轉(zhuǎn)到登錄頁面</h2>");
        setTimeout("location.href='login.html'",5000);//使用setTimeout延遲5秒后自動跳轉(zhuǎn)
    }
    else{
        document.write("<h2>大獎趕快拿啦!筆記本!數(shù)碼相機!</h2>");
    }
</script>
//3.login頁面
<div>登錄頁面</div

參考資料:剛需!document.referrer 詳解

六、Document對象的常用方法

名稱 說明
getElementById() 返回對擁有指定id的第一個對象的引用
getElementsByName() 返回帶有指定名稱的對象的集合
getElementsByTagName() 返回帶有指定標(biāo)簽名的對象的集合
write() 向文檔寫文本、HTML表達式或JavaScript代碼

案例:選擇顏色

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>選擇顏色</title>
    <style type="text/css">
        #color{font-family: "微軟雅黑";
        font-size: 16px;
        color: #ff0000;
        font-weight: bold;
        }
    </style>
</head>
<body>
<div>
    本次選擇的顏色是:<span id="color"></span>
    <input type="button" value="選擇顏色" onclick="selColor();">
</div>
<script type="text/javascript">
    function selColor(){
        var color=Array("紅色","黃色","藍色","綠色","橙色","青色","紫色");
        var num=Math.ceil(Math.random()*7)-1;
        document.getElementById("color").innerHTML=color[num];
    }
</script>
</body>
</html>

案例:document對象的應(yīng)用

<style type="text/css">
        body,input,div,p,{margin: 0;padding: 0;}
        body{font-size: 14px; font-family: "微軟雅黑"; line-height: 25px;}
        .content{width: 550px; margin: 0 auto;}
        .content img{ float: left; width: 150px;}
        .r{float: left; width: 400px;}
        input[name="changeBook"]{
            width: 100px;
            height: 28px;
            line-height: 28px;
            text-align: center;
            font-size: 14px; font-family: "微軟雅黑";
            margin: 10px 0 10px 0;
        }
        input[name="season"]{
            width: 50px; text-align: center;
        }
    </style>
//html代碼
<div class="content">
    <img src="images/book.jpg" alt="島上書店"/>
    <div class="r">
        <div id="book">書名:島上書店</div>
        <input name="changeBook" value="換換名稱" type="button" onclick="alterBook();" /><br>
        四季名稱:
        <input name="season" type="text" value="春" />
        <input name="season" type="text" value="夏" />
        <input name="season" type="text" value="秋" />
        <input name="season" type="text" value="冬" /><br><br>
        <input name="b2" type="button" value="input內(nèi)容" onclick= "all_input()" />
        <input name="b3" type="button" value="四季名稱" onclick="s_input()" />
        <input name="b4" type="button" value="清空頁面內(nèi)容" onclick="clearAll()" />
        <p id="replace"></p>
    </div>
</div>

//js代碼
<script  type="text/javascript">
    //動態(tài)改變層、標(biāo)簽中的內(nèi)容
    function alterBook(){
        document.getElementById("book").innerHTML="現(xiàn)象級全球暢銷書";
    }
//訪問相同標(biāo)簽的元素
    function all_input(){
        var aInput=document.getElementsByTagName("input");
        var sStr="";
        for(var i=0;i<aInput.length;i++){
            sStr+=aInput[i].value+"&nbsp;&nbsp;";
        }
        document.getElementById("replace").innerHTML=sStr;
    }
    //訪問相同name的元素
    function s_input(){
        var aInput=document.getElementsByName("season");
        var sStr="";
        for(var i=0;i<aInput.length;i++){
            sStr+=aInput[i].value+"&nbsp;&nbsp;";
        }
        document.getElementById("replace").innerHTML=sStr;
    }
    function clearAll(){
        document.write("");
    }
</script>

七、定時函數(shù)

//使用Date對象的方法顯示當(dāng)前時間的小時、分鐘和秒
function disptime(){
var today = new Date();  
var hh = today.getHours(); 
var mm = today.getMinutes();
var ss = today.getSeconds();
document.getElementById("myclock").innerHTML="現(xiàn)在是:"+hh +":"+mm+": "+ss;
}
disptime();

1.setTimeout()

//語法
setTimeout("調(diào)用的函數(shù)",等待的毫秒數(shù))

//示例
var  myTime=setTimeout("disptime() ", 1000 ); //1秒(1000毫秒)之后執(zhí)行函數(shù)disptime()一次

2.setInterval()

//語法
setInterval("調(diào)用的函數(shù)",間隔的毫秒數(shù))

//示例
var  myTime=setInterval("disptime() ", 1000 ); //每隔1秒(1000毫秒)執(zhí)行函數(shù)disptime()一次

如果要多次調(diào)用,使用setInterval()或者讓disptime()自身再次調(diào)用setTimeout()
兩個定時函數(shù)的區(qū)別;

  • setTimeout()在等待指定時間后執(zhí)行函數(shù),且只執(zhí)行一次;
  • setInterval()是每指導(dǎo)間也不是時間后執(zhí)行一次函數(shù),循 環(huán)執(zhí)行,所以時鐘例子使用setInterval();

3.clearTimeout()

//語法
clearTimeout(setTimeOut()返回的ID值)

//示例
var  myTime=setTimeout("disptime() ", 1000 );
clearTimeout(myTime);

4.clearInterval()

//語法
clearInterval(setInterval()返回的ID值)

//示例
var  myTime=setInterval("disptime() ", 1000 );
clearInterval(myTime);

兩者之間的區(qū)別;

  • clearTimeout()清除由setTimeout()設(shè)置的定時;
  • clearInterval()清除由setInterval()設(shè)置的定時;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容