【2020Python修煉記】前端開發之 JavaScript 的 BOM 和 DOM 操做

【目錄】

1、BOM操做

一、window 對象

二、window 子對象

三、history 對象

四、location 對象(掌握)

五、彈出框

六、計時器相關

2、DOM操做

一、DOM相關概念

二、查找標籤

三、節點操做

四、獲取值操做

五、class、css操做

六、原生JS事件

 

(如下是使用mac筆記本中的瀏覽器(檢查元素的 console 界面)進行的操做)

1、BOM操做

 瀏覽器對象模型 Browser Object Model

js代碼操做 瀏覽器

一、window對象

# window對象 window對象指代的就是瀏覽器窗口 window.innerHeight 瀏覽器窗口的高度 900 window.innerWidth 瀏覽器窗口的寬度 1680 
# 新建窗口打開頁面 第二個參數寫空便可 第三個參數寫新建的窗口的大小和位置
window.open(url,target,features)
eg:window.open('https://www.baidu.com/','','height=400px,width=400px,top=400px,left=400px') # 擴展父子頁面通訊 window.opener() 瞭解 window.close() 關閉當前頁面

二、window子對象

window.navigator.appName
"Netscape"css


window.navigator.appVersion
"5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"html

window.navigator.userAgent      # 用來表示當前是不是一個瀏覽器
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"web

 

"""瀏覽器

擴展:防爬措施
1.最簡單最經常使用的一個就是 校驗當前請求的發起者是不是一個瀏覽器app

(有如下配置信息,說明是瀏覽器)
userAgent
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36ide

二、如何破解該措施
在你的代碼中加上上面的user-agent配置便可
"""函數

window.navigator.platform
"MacIntel"測試

# 若是是window的子對象 那麼window能夠省略不寫網站

三、history對象

window.history.back()  回退到上一頁
window.history.forward()  前進到下一頁

# 對應的就是你使用的瀏覽器左上方的兩個的箭頭

四、location對象(掌握)

window.location.href   # 獲取當前頁面的url
window.location.href = url   # 跳轉到指定的url
window.location.reload()   # 屬性頁面 瀏覽器左上方的小圓圈

五、彈出框

警告框

alert('請謹慎訪問此網站')

 

確認框

confirm('你肯定加入遊戲嗎?')

false

confirm('你肯定進入下一輪遊戲嗎?')

true

 

提示框

prompt('歡迎光臨','請先登入')

"歡迎加入"  

 

六、計時器相關

 一、過一段時間以後觸發(一次)

setTimeout(func1,3000)

clearTimeout(t)

二、每隔一段時間觸發一次(循環)

setInterval(func2,3000)

clearInterval(t)

<script>

// 一、過一段時間以後觸發(一次) function func1() { alert(123) } let t = setTimeout(func1,3000); // 毫秒爲單位 3秒以後自動執行func1函數 clearTimeout(t) // 取消定時任務 若是你想要清除定時任務 須要日前用變量指代定時任務

//二、每隔一段時間觸發一次(循環) function func2() { alert(123) } function show(){ let t = setInterval(func2,3000); // 每隔3秒執行一次 function inner(){ clearInterval(t) // 清除定時器 } setTimeout(inner,9000) // 9秒中以後觸發 } show() </script>

 

2、DOM操做

 文檔對象模型 Document Object Model

js代碼操做 標籤

一、DOM相關概念

# DOM樹的概念

全部的標籤均可以稱之爲是節點

# JavaScript 能夠經過DOM建立動態的 HTML:

JavaScript 可以改變頁面中的全部 HTML 元素
JavaScript 可以改變頁面中的全部 HTML 屬性
JavaScript 可以改變頁面中的全部 CSS 樣式
JavaScript 可以對頁面中的全部事件作出反應

# DOM操做

操做的是標籤 而一個html頁面上的標籤有不少 

1.先學如何查找標籤
2.再學DOM操做標籤

# DOM操做須要用關鍵字 document 起首

二、查找標籤

(1)直接查找

""" id查找 類查找 標籤查找 """
# 注意三個方法的返回值是不同的
document.getElementById('d1') <div id=​"d1">​…​</div>document.getElementsByClassName('c1') # 注意 類查找和標籤查找 getElementsBy… —— Element 寫的是複數 Elements 
HTMLCollection [p.c1]0: p.c1length: 1__proto__: HTMLCollection

document.getElementsByTagName('div')
HTMLCollection(
3) [div#d1, div, div, d1: div#d1] let divEle = document.getElementsByTagName('div')[1] divEle <div>​ div>div​ </div>

""" 當你用變量名指代標籤對象的時候 通常狀況下都推薦你書寫成 xxxEle divEle aEle pEle """

 

(2)間接查找

let pEle = document.getElementsByClassName('c1')[0]  # 注意是否須要索引取值
 pEle.parentElement # 拿父節點
<div id=​"d1">​"div
    "<div>​div>div​</div>​<p class=​"c1">​…​</p>​<p>​div>p​</p>​</div>​
pEle.parentElement.parentElement <body>​…​</body>
pEle.parentElement.parentElement.parentElement
<html lang=​"en">​<head>​…​</head>​<body>​…​</body>​</html>
pEle.parentElement.parentElement.parentElement.parentElement null let divEle
= document.getElementById('d1') divEle.children # 獲取全部的子標籤 divEle.children[0] <div>​div>div​</div>divEle.firstElementChild <div>​div>div​</div>divEle.lastElementChild <p>​div>p​</p>divEle.nextElementSibling # 同級別下面第一個 <div>​div下面div​</div>divEle.previousElementSibling # 同級別上面第一個 <div>​div上面的div​</div>​

 

三、節點操做

(1) 

document.createElement('img')  # 建立標籤
""" 經過DOM操做動態的建立img標籤 而且給標籤加屬性 最後將標籤添加到文本中 """ let imgEle = document.createElement('img')  # 建立標籤
 imgEle.src = '111.png'  # 給標籤設置默認的屬性
"111.png" imgEle imgEle.username = 'jason'  # 自定義的屬性沒辦法點的方式直接設置
"jason" imgEle <img src=​"111.png">​ imgEle.setAttribute('username','jason')   # 既能夠設置自定義的屬性也能夠設置默認的書寫
undefined imgEle <img src=​"111.png" username=​"jason">​ imgEle.setAttribute('title','一張圖片') imgEle <img src=​"111.png" username=​"jason" title=​"一張圖片">​ let divEle = document.getElementById('d1') undefined divEle.appendChild(imgEle) # 標籤內部添加元素(尾部追加)
<img src=​"111.png" username=​"jason" title=​"一張圖片">​

(2)url

""" 建立a標籤 設置屬性 設置文本 添加到標籤內部 添加到指定的標籤的上面 """ let aEle = document.createElement('a') aEle <a>​</a>​ aEle.href = 'https://www.mzitu.com/'
"https://www.mzitu.com/" aEle <a href=​"https:​/​/​www.mzitu.com/​">​</a>​ aEle.innerText = '點我有你好看!'  # 給標籤設置文本內容
"點我有你好看!" aEle <a href=​"https:​/​/​www.mzitu.com/​">​點我有你好看!​</a>​ let divEle = document.getElementById('d1') undefined let pEle = document.getElementById('d2') undefined divEle.insertBefore(aEle,pEle) # 添加標籤內容指定位置添加
<a href=​"https:​/​/​www.mzitu.com/​">​點我有你好看!​</a>​

(3)

""" 額外補充 appendChild() removeChild() replaceChild() setAttribute() 設置屬性 getAttribute() 獲取屬性 removeAttribute() 移除屬性 """

# innerText與innerHTML
divEle.innerText  # 獲取標籤內部全部的文本
"div 點我有你好看!
div>p div>span"  divEle.innerHTML # 內部文本和標籤都拿到
"div
        <a href="https://www.mzitu.com/">點我有你好看!</a><p id="d2">div&gt;p</p>
        <span>div&gt;span</span>
    "  divEle.innerText = 'heiheihei'
"heiheihei" divEle.innerHTML = 'hahahaha'
"hahahaha" divEle.innerText = '<h1>heiheihei</h1>'  # 不識別html標籤
"<h1>heiheihei</h1>" divEle.innerHTML = '<h1>hahahaha</h1>'  # 識別html標籤
"<h1>hahahaha</h1>"

 

四、獲取值操做

# 獲取用戶數據標籤內部的數據
let seEle = document.getElementById('d2') seEle.value "111" seEle.value "333" let inputEle = document.getElementById('d1') inputEle.value
# 如何獲取用戶上傳的文件數據
let fileEle = document.getElementById('d3') fileEle.value # 沒法獲取到文件數據
"C:\fakepath\02_測試路由.png" fileEle.files FileList {0: File, length: 1}0: File {name: "02_測試路由.png", lastModified: 1557043082000, 
lastModifiedDate: Sun May 05 2019 15:58:02 GMT+0800 (中國標準時間),
webkitRelativePath: "", size: 29580, …}length: 1__proto__: FileList fileEle.files[0] # 獲取文件數據 File {name: "02_測試路由.png", lastModified: 1557043082000,
lastModifiedDate: Sun May 05 2019 15:58:02 GMT+0800 (中國標準時間), webkitRelativePath: "", size: 29580, …}

 

五、class、css操做  

let divEle = document.getElementById('d1') undefined divEle.classList # 獲取標籤全部的類屬性
DOMTokenList(3) ["c1", "bg_red", "bg_green", value: "c1 bg_red bg_green"] divEle.classList.remove('bg_red')  # 移除某個類屬性
undefined divEle.classList.add('bg_red')  # 添加類屬性
undefined divEle.classList.contains('c1')  # 驗證是否包含某個類屬性
true divEle.classList.contains('c2') false divEle.classList.toggle('bg_red')  # 有則刪除無則添加
false divEle.classList.toggle('bg_red') true divEle.classList.toggle('bg_red') false divEle.classList.toggle('bg_red') true divEle.classList.toggle('bg_red') false divEle.classList.toggle('bg_red') true # DOM操做操做標籤樣式 統一先用style起首
let pEle = document.getElementsByTagName('p')[0] undefined pEle.style.color = 'red'
"red" pEle.style.fontSize = '28px'
"28px" pEle.style.backgroundColor = 'yellow'
"yellow" pEle.style.border = '3px solid red'
"3px solid red"

 

六、原生JS事件

(1) 什麼是事件,以及綁定事件的兩種方法

""" 達到某個事先設定的條件 自動觸發的動做 """ # 綁定事件的兩種方式 <button onclick="func1()">點我</button>
<button id="d1">點我</button>

<script>
    // 第一種綁定事件的方式
    function func1() { alert(111) } // 第二種
 let btnEle = document.getElementById('d1'); btnEle.onclick = function () { alert(222) } </script> """ script標籤既能夠放在head內 也能夠放在body內 可是一般狀況下都是放在body內的最底部 # 等待瀏覽器窗口加載完畢以後再執行代碼 window.onload = function () { // 第一種綁定事件的方式 function func1() { alert(111) } // 第二種 let btnEle = document.getElementById('d1'); btnEle.onclick = function () { alert(222) } } """

(2)應用栗子

開關燈案例

<div id="d1" class="c1 bg_red bg_green"></div>
    <button id="d2">變色</button>

    <script> let btnEle = document.getElementById('d2') let divEle = document.getElementById('d1') btnEle.onclick = function () { // 綁定點擊事件
            // 動態的修改div標籤的類屬性
 divEle.classList.toggle('bg_red') } </script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        .c1 {
            height: 400px;
            width: 400px;
            border-radius: 50%;
        }
        .bg_green {
            background-color: greenyellow;
        }
        .bg_red {
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="d1" class="c1 bg_red bg_green"></div>
    <button id="d2">變色</button>

    <script>
        let btnEle = document.getElementById('d2')
        let divEle = document.getElementById('d1')
        btnEle.onclick = function () {  // 綁定點擊事件
            // 動態的修改div標籤的類屬性
            divEle.classList.toggle('bg_red')
        }
    </script>
</body>
</html>
詳細代碼

 

input框獲取焦點失去焦點案例

<input type="text" value="老闆 去嗎?" id="d1">

<script> let iEle = document.getElementById('d1') // 獲取焦點事件
 iEle.onfocus = function () { // 將input框內部值去除
 iEle.value = ''
        // 點value就是獲取 等號賦值就是設置
 } // 失去焦點事件
 iEle.onblur = function () { // 給input標籤重寫賦值
 iEle.value = '沒錢 不去!' } </script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
<input type="text" value="老闆 去嗎?" id="d1">

<script>
    let iEle = document.getElementById('d1')
    // 獲取焦點事件
    iEle.onfocus = function () {
        // 將input框內部值去除
        iEle.value = ''
        //  點value就是獲取   等號賦值就是設置
    }
    // 失去焦點事件
    iEle.onblur = function () {
        // 給input標籤重寫賦值
        iEle.value = '沒錢 不去!'
    }
</script>
</body>
</html>
View Code

 

實時展現當前時間

<input type="text" id="d1" style="display: block;height: 50px;width: 200px">
<button id="d2">開始</button>
<button id="d3">結束</button>

<script>
    // 先定義一個全局存儲定時器的變量
 let t = null let inputEle = document.getElementById('d1') let startBtnEle = document.getElementById('d2') let endBtnEle = document.getElementById('d3') // 1 訪問頁面以後 將訪問的時間展現到input框中
    // 2 動態展現當前時間
    // 3 頁面上加兩個按鈕 一個開始 一個結束
    function showTime() { let currentTime = new Date(); inputEle.value = currentTime.toLocaleString() } startBtnEle.onclick = function () { // 限制定時器只能開一個
        if(!t){ t = setInterval(showTime,1000) // 每點擊一次就會開設一個定時器 而t只指代最後一個
 } } endBtnEle.onclick = function () { clearInterval(t) // 還應該將t重置爲空
 t = null } </script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
<input type="text" id="d1" style="display: block;height: 50px;width: 200px">
<button id="d2">開始</button>
<button id="d3">結束</button>

<script>
    // 先定義一個全局存儲定時器的變量
    let t = null
    let inputEle = document.getElementById('d1')
    let startBtnEle = document.getElementById('d2')
    let endBtnEle = document.getElementById('d3')
    // 1 訪問頁面以後 將訪問的時間展現到input框中
    // 2 動態展現當前時間
    // 3 頁面上加兩個按鈕 一個開始 一個結束
    function showTime() {
        let currentTime = new Date();
        inputEle.value = currentTime.toLocaleString()
    }

    startBtnEle.onclick = function () {
        // 限制定時器只能開一個
        if(!t){
            t = setInterval(showTime,1000)  // 每點擊一次就會開設一個定時器 而t只指代最後一個
        }
    }
    endBtnEle.onclick = function () {
        clearInterval(t)
        // 還應該將t重置爲空
        t = null
    }
</script>
</body>
</html>
View Code

 

省市聯動

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<select name="" id="d1">
    <option value="" selected disabled>--請選擇--</option>
</select>
<select name="" id="d2"></select>

<script>
    let proEle = document.getElementById('d1')
    let cityEle = document.getElementById('d2')
    // 先模擬省市數據
    data = {
        "河北": ["廊坊", "邯鄲",'唐山'],
        "北京": ["朝陽區", "海淀區",'昌平區'],
        "山東": ["威海市", "煙臺市",'臨沂市'],
        '上海':['浦東新區','靜安區','黃浦區'],
        '深圳':['南山區','寶安區','福田區']
    };
    // 選for循環獲取省
    for(let key in data){
        // 將省信息作成一個個option標籤 添加到第一個select框中
        // 1 建立option標籤
        let opEle = document.createElement('option')
        // 2 設置文本
        opEle.innerText = key
        // 3 設置value
        opEle.value = key  // <option value="省">省</option>
        // 4 將建立好的option標籤添加到第一個select中
        proEle.appendChild(opEle)
    }
    // 文本域變化事件  change事件
    proEle.onchange = function () {
        // 先獲取到用戶選擇的省
        let currentPro = proEle.value
        // 獲取對應的市信息
        let currentCityList = data[currentPro]
        // 清空市select中全部的option
        cityEle.innerHTML = ''
        // 本身加一個請選擇
        let ss = "<option disabled selected>請選擇</option>"
        // let oppEle = document.createElement('option')
        // oppEle.innerText = '請選擇'
        // oppEle.setAttribute('selected','selected')
        cityEle.innerHTML = ss

        // for循環全部的市 渲染到第二個select中
        for (let i=0;i<currentCityList.length;i++){
            let currentCity = currentCityList[i]
            // 1 建立option標籤
            let opEle = document.createElement('option')
            // 2 設置文本
            opEle.innerText = currentCity
            // 3 設置value
            opEle.value = currentCity  // <option value="省">省</option>
            // 4 將建立好的option標籤添加到第一個select中
            cityEle.appendChild(opEle)
        }
    }
</script>
</body>
</html>
View Code

 

 

參考閱讀:

https://www.cnblogs.com/xiaoyuanqujing/articles/11670078.html

相關文章
相關標籤/搜索