JavaScript第五天

<meta charset="utf-8">

<article class="_2rhmJa">

創(chuàng)建元素的三種方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<button>點擊</button>
<p>abc</p>
<div class="inner"></div>
<div class="create"></div>
<script>
    // window.onload = function () {
    //     document.write('<div>123</div>')
    // }
    // document.write創(chuàng)建元素如果頁面文檔流加載完畢,在調(diào)用這句話會導(dǎo)致頁面重繪
    // var btn = document.querySelector('button')
    // btn.onclick = function () {
    //     document.write('<div>123</div>')
    // }
    // 2\. innerHTML
    var inner = document.querySelector('.inner')
    // 拼接字符串
    // for (var i = 0; i <100 ; i++) {
    //     inner.innerHTML += '<a href="#">百度</a>'
    // }
    // 使用數(shù)組的方式
    var arr = [];
    for (var i = 0; i <100 ; i++) {
        // 數(shù)組元素的添加
        arr.push('<a href="#">百度</a>')
    }
    // 將數(shù)組連接起來
    inner.innerHTML = arr.join('')
    //
    var create = document.querySelector('.create')

    for (var i = 0; i <100 ; i++) {
        var a =  document.createElement('a')
        a.innerHTML = '百度'
        a.href = "#"
        create.appendChild(a)
    }

</script>
</body>
</html>

拼接效率測試

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function fn() {
       var d1 = +new Date() // + 號相當(dāng)于將時間對象做了隱士轉(zhuǎn)換

       var str = '';
        for (var i = 0; i <1000 ; i++) {
            document.body.innerHTML += '<div style="width: 100px; height: 2px; border: 1px solid blue"></div>'
        }

        var d2 = +new Date()
        console.log(d2-d1)
    }
    fn();
</script>

</body>
</html>

數(shù)組拼接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function fn() {
       var d1 = +new Date() // + 號相當(dāng)于將時間對象做了隱士轉(zhuǎn)換

       var arr = [];
        for (var i = 0; i <1000 ; i++) {
            // document.body.innerHTML += '<div style="width: 100px; height: 2px; border: 1px solid blue"></div>'
            arr.push('<div style="width: 100px; height: 2px; border: 1px solid blue"></div>')
        }
        document.body.innerHTML = arr.join('');
        var d2 = +new Date()
        console.log(d2-d1)
    }
    fn();
</script>

</body>
</html>

createElement

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function fn() {
       var d1 = +new Date() // + 號相當(dāng)于將時間對象做了隱士轉(zhuǎn)換

       var arr = [];
        for (var i = 0; i <1000 ; i++) {
            // document.body.innerHTML += '<div style="width: 100px; height: 2px; border: 1px solid blue"></div>'
            arr.push('<div style="width: 100px; height: 2px; border: 1px solid blue"></div>')
        }
        document.body.innerHTML = arr.join('');
        var d2 = +new Date()
        console.log(d2-d1)
    }
    fn();
</script>
</body>
</html>

DOM的核心總結(jié)

關(guān)于dom操作,我們主要針對于元素的操作。主要有創(chuàng)建、增、刪、改、查、屬性操作、事件操作。
  • 創(chuàng)建

  • 增加

  • 屬性操作


    <meta charset="utf-8">

事件操作(重點)

注冊事件

事件監(jiān)聽

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>傳統(tǒng)注冊事件</button>
<button>方法監(jiān)聽注冊事件</button>
<script>
    var btns = document.querySelectorAll('button')
    // 傳統(tǒng)  唯一
    btns[0].onclick = function () {
        alert('haha')
    }
    btns[0].onclick = function () {
        alert('hehe')
    }
    // 方法監(jiān)聽注冊事件
    // 不帶on
    btns[1].addEventListener('click', function () {
        alert('ahaha')
    })
    btns[1].addEventListener('click', function () {
        alert('ahehe')
    })

</script>

</body>
</html>

刪除事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
   var divs = document.querySelectorAll('div')
    divs[0].onclick = function () {
        alert('哈哈')
        // 傳統(tǒng)刪除事件的方式
        this.onclick = null;
    }
    divs[1].addEventListener('click', fn) // 傳函數(shù)名,不是調(diào)用
    function fn() {
        alert('haha')
        this.removeEventListener('click', fn)
    }
</script>
</body>
</html>

DOM事件流

html中的標(biāo)簽都是相互嵌套的,我們可以將元素想象成一個盒子裝一個盒子,document是最外面的大盒子。
當(dāng)你單擊一個div時,同時你也單擊了div的父元素,甚至整個頁面。
那么是先執(zhí)行父元素的單擊事件,還是先執(zhí)行div的單擊事件 ??

最終,w3c 采用折中的方式,平息了戰(zhàn)火,制定了統(tǒng)一的標(biāo)準(zhǔn) —--— 先捕獲再冒泡。現(xiàn)代瀏覽器都遵循了此標(biāo)準(zhǔn),所以當(dāng)事件發(fā)生時,會經(jīng)歷3個階段。

我們向水里面扔一塊石頭,首先它會有一個下降的過程,這個過程就可以理解為從最頂層向事件發(fā)生的最具體元素(目標(biāo)點)的捕獲過程;之后會產(chǎn)生泡泡,會在最低點( 最具體元素)之后漂浮到水面上,這個過程相當(dāng)于事件冒泡。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .father {
            overflow: hidden;
            width: 300px;
            height: 300px;
            margin: 100px auto;
            background-color: pink;
            text-align: center;
        }

        .son {
            width: 200px;
            height: 200px;
            margin: 50px;
            background-color: blue;
            line-height: 200px;
            color: #fff;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son">son盒子</div>
</div>
<script>
    // dom 事件流三個階段
    // 1\. js只能執(zhí)行捕獲或者冒泡其中的一個
    // 2、 onclick 只有冒泡
    // addEventListener(type, func, bool)
    // 第三個參數(shù) 是true 處于捕獲階段
    // document -> html -> body -> father -> son

    // var son = document.querySelector('.son')
    // son.addEventListener('click', function () {
    //     alert('son')
    // }, true)
    // var father = document.querySelector('.father')
    // father.addEventListener('click', function () {
    //     alert('father')
    // }, true)
    //
    // document.addEventListener('click', function () {
    //     alert('document')
    // },true)
    //
    // 冒泡階段 第三個參數(shù) 是false或者不寫 處于冒泡階段
    // son -> father -> body -> html -> document
    var son = document.querySelector('.son')
    son.addEventListener('click', function () {
        alert('son')
    }, false)
    var father = document.querySelector('.father')
    father.addEventListener('click', function () {
        alert('father')
    }, false)

    document.addEventListener('click', function () {
        alert('document')
    },false)

</script>

</body>
</html>

事件對象

什么是事件對象
事件發(fā)生后,跟事件相關(guān)的一系列信息數(shù)據(jù)的集合都放到這個對象里面,這個對象就是事件對象。
比如:

  1. 誰綁定了這個事件。
  2. 鼠標(biāo)觸發(fā)事件的話,會得到鼠標(biāo)的相關(guān)信息,如鼠標(biāo)位置。
  3. 鍵盤觸發(fā)事件的話,會得到鍵盤的相關(guān)信息,如按了哪個鍵。
事件對象的使用

事件觸發(fā)發(fā)生時就會產(chǎn)生事件對象,并且系統(tǒng)會以實參的形式傳給事件處理函數(shù)。
所以,在事件處理函數(shù)中聲明1個形參用來接收事件對象。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div>123</div>
<script>
    var div = document.querySelector('div')
    // div.onclick = function (event) {
    //     console.log(event);
    // }

    div.addEventListener('click', function (e) {
        console.log(e);
    })

    // 1\. event 就是一個事件對象 寫到我們偵聽函數(shù)的 小括號里面 當(dāng)形參來看
    // 2\. 事件對象只有有了事件才會存在,它是系統(tǒng)給我們自動創(chuàng)建的,不需要我們傳遞參數(shù)
    // 3\. 事件對象 是 我們事件的一系列相關(guān)數(shù)據(jù)的集合 跟事件相關(guān)的 比如鼠標(biāo)點擊里面就包含了鼠標(biāo)的相關(guān)信息,鼠標(biāo)坐標(biāo)啊,如果是鍵盤事件里面就包含的鍵盤事件的信息 比如 判斷用戶按下了那個鍵
    // 4\. 這個事件對象我們可以自己命名 比如 event 、 evt、 e
</script>
</body>
</html>

事件對象的屬性和方法

e.target 和 this 的區(qū)別

  • this 是事件綁定的元素(綁定這個事件處理函數(shù)的元素) 。
  • e.target 是事件觸發(fā)的元素。
常情況下terget 和 this是一致的,
但有一種情況不同,那就是在事件冒泡時(父子元素有相同事件,單擊子元素,父元素的事件處理函數(shù)也會被觸發(fā)執(zhí)行),
    這時候this指向的是父元素,因為它是綁定事件的元素對象,
    而target指向的是子元素,因為他是觸發(fā)事件的那個具體元素對象。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div>123</div>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<script>
    var div = document.querySelector('div')

    div.addEventListener('click', function (e) {
        // 沒區(qū)別
        console.log(e.target);
        console.log('+++++++++++++++');
        console.log(this)
    })
    var ul = document.querySelector('ul')
    ul.addEventListener('click', function (e) {
        // 綁定ul 指定的是ul
        console.log(this)
        console.log('+++++++++++++++');
        console.log(e.currentTarget)
        console.log('+++++++++++++++');
        // 誰觸發(fā)了那個事件,  e.target就指向誰
        console.log(e.target);

    })

</script>
</body>
</html>

阻止默認(rèn)行為

html中一些標(biāo)簽有默認(rèn)行為,例如a標(biāo)簽被單擊后,默認(rèn)會進行頁面跳轉(zhuǎn)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>123</div>
<a >百度</a>
<form action="http://www.baidu.com">
    <input type="submit" value="提交" name="sub">
</form>
<script>
    var div = document.querySelector('div')
    div.addEventListener('click', fn)
    div.addEventListener('mouseover', fn)
    div.addEventListener('mouseout', fn)

    function fn(e) {
        console.log(e.type);
    }
    // 阻止a 鏈接跳轉(zhuǎn)
    var a = document.querySelector('a')
    // a.addEventListener('click', function (e) {
    //     e.preventDefault() // 標(biāo)準(zhǔn)阻止寫法
    // })
    a.onclick =  function (e) {
        // e.preventDefault()
        //  return false 只有 在傳統(tǒng)注冊時候才能生效
        return false;

    }

</script>
</body>
</html>

阻止事件冒泡

事件冒泡本身的特性,會帶來的壞處,也會帶來的好處。

事件委托

事件冒泡本身的特性,會帶來的壞處,也會帶來的好處。
把事情委托給別人,代為處理。
事件委托也稱為事件代理,在 jQuery 里面稱為事件委派。
說白了就是,不給子元素注冊事件,給父元素注冊事件,把處理代碼在父元素的事件中執(zhí)行。

事件委托的原理

給父元素注冊事件,利用事件冒泡,當(dāng)子元素的事件觸發(fā),會冒泡到父元素,然后去控制相應(yīng)的子元素。

事件委托的作用

  • 我們只操作了一次 DOM ,提高了程序的性能。
  • 動態(tài)新創(chuàng)建的子元素,也擁有事件。
<ul>
    <li>點我點我快點我!</li>
    <li>點我點我快點我!</li>
    <li>點我點我快點我!</li>
    <li>點我點我快點我!</li>
    <li>點我點我快點我!</li>
</ul>
<script>
    var ul = document.querySelector('ul')
    // 事件委托的原理, 給父節(jié)點添加偵聽器,
    // 利用事件冒泡去影響每一個子節(jié)點
    ul.addEventListener('click', function (e) {
        // alert('點了點了')
        // e.target 可以得到我們點擊的對象
        e.target.style.backgroundColor = 'blue';
    })

    // 給父元素注冊事件,利用事件冒泡,當(dāng)子元素的事件觸發(fā),會冒泡到父元素,
    // 然后去控制相應(yīng)的子元素。
</script>

常用鼠標(biāo)事件

HTML防止別人分享案例

尊敬的騰訊會員,此乃九陽神功秘籍,不能給別人分享
<script>
    // contextmenu 可以禁止右鍵菜單
    document.addEventListener('contextmenu', function (e) {
        e.preventDefault()
    })
    // selectstart禁止選中文字
    document.addEventListener('selectstart', function (e) {
        e.preventDefault()
    })
</script>

鼠標(biāo)事件對象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            height: 3000px;
        }
    </style>
</head>
<body>
<script>
    document.addEventListener('click', function (e) {
        // 1\. client 鼠標(biāo)在可視區(qū)的x 和 y 的坐標(biāo)
        console.log(e.clientX)
        console.log(e.clientY)
        console.log('++++++++++++++++++++++++++++++++++++')
        // 2 page 鼠標(biāo)在頁面文檔的x 和 y 的坐標(biāo)
        console.log(e.pageX)
        console.log(e.pageY)
        console.log('++++++++++++++++++++++++++++++++++++')
        // 3 screen 鼠標(biāo)在電腦屏幕的x 和 y 的坐標(biāo)
        console.log(e.screenX)
        console.log(e.screenY)
        console.log('++++++++++++++++++++++++++++++++++++')

    })
</script>
</body>
</html>

案例:跟隨鼠標(biāo)的天使

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        img{
            position: absolute;
            top: 2px;
        }
        body{
            height: 3000px;
        }
    </style>
</head>
<body>
<img src="../imgs/angel.gif" alt="">
<script>
    var pic = document.querySelector('img')
    document.addEventListener('mousemove', function (e) {
        // console.log(1)
        var x = e.pageX;
        var y = e.pageY;
        console.log('x坐標(biāo)的值是'+ x + 'y坐標(biāo)是' + y)
        pic.style.left = x - 40 + 'px';
        pic.style.top = y - 30 + 'px'
    })
</script>
</body>
</html>

鍵盤事件

<script>
    document.addEventListener('keyup', function () {
        console.log('我彈起了')
    })

    document.addEventListener('keydown', function () {
        console.log('我down了')
    })
</script>

模擬京東按鍵輸入內(nèi)容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text">
<script>
    var search = document.querySelector('input')
    document.addEventListener('keyup', function (e) {
        console.log(e.keyCode)
        if(e.keyCode === 83){
            search.focus();
        }
    })
</script>
</body>
</html>

模擬京東快遞單號查詢

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .search {
            position: relative;
            width: 178px;
            margin: 100px;
        }

        .con {
            display: none;
            position: absolute;
            top: -40px;
            width: 171px;
            border: 1px solid rgba(0, 0, 0, .2);
            box-shadow: 0 2px 4px rgba(0, 0, 0, .2);
            padding: 5px 0;
            font-size: 18px;
            line-height: 20px;
            color: #333;
        }

        .con::before {
            content: '';
            width: 0;
            height: 0;
            position: absolute;
            top: 28px;
            left: 18px;
            border: 8px solid #000;
            border-style: solid dashed dashed;
            border-color: #fff transparent transparent;
        }
    </style>
</head>
<body>
<div class="search">
    <div class="con">123</div>
    <input type="text" placeholder="請輸入您的快遞單號" class="jd">
</div>
<script>
    var con = document.querySelector('.con')
    var jd_input = document.querySelector('.jd')
    jd_input.addEventListener('keyup',function () {
        console.log('輸入啦')
        if (this.value == ''){
            con.style.display = 'none';
        }else {
            con.style.display = 'block';
            con.innerText = this.value;
        }

        // 當(dāng)我們失去焦點 的時候隱藏div盒子哦
        jd_input.addEventListener('blur', function () {
            con.style.display = 'none';

        })
        // 當(dāng)我們獲取焦點 的時候顯示div盒子哦
        jd_input.addEventListener('focus', function () {
            if (this.value !== '') {
                con.style.display = 'block';
            }
        })
    })

</script>
</body>
</html>

BOM

  • BOM(Browser Object Model)即瀏覽器對象模型,它提供了獨立于內(nèi)容而與瀏覽器窗口進行交互的對象,其核心對象是 window。
  • BOM 由一系列相關(guān)的對象構(gòu)成,并且每個對象都提供了很多方法與屬性。
  • BOM 缺乏標(biāo)準(zhǔn),JavaScript 語法的標(biāo)準(zhǔn)化組織是 ECMA,DOM 的標(biāo)準(zhǔn)化組織是 W3C,BOM 最初是Netscape 瀏覽器標(biāo)準(zhǔn)的一部分。

BOM的構(gòu)成

頂級對象window

window對象的常見事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var num = 10;
    console.log(num);
    console.log(window.num);
    function fn() {
        console.log('fn');

    }
    fn();
    window.fn();

    console.dir(window);

</script>
</body>
</html>

window對象的常見事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // window.onload = function () {
        //     var btn = document.querySelector('button')
        //     btn.addEventListener('click', function () {
        //         alert('點擊我')
        //     })
        // }
        // window.onload = function () {
        //     alert('hehe')
        // }
        window.addEventListener('load', function () {
            var btn = document.querySelector('button')
            btn.addEventListener('click', function () {
                alert('點擊我')
            })
        })
        window.addEventListener('load', function () {
            alert('window')
        })
        //  DOMContentLoaded 是dom加載完畢,  加載速度比load更快一些
        document.addEventListener('DOMContentLoaded', function () {
            alert('DOMContentLoaded')
        })

    </script>
</head>
<body>
<button>點擊</button>

</body>
</html>

調(diào)整窗口大小事件

?著作權(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)容