JS事件与定时器

138 阅读4分钟

概念

-JS 事件(event)是在页面中通过某些动作触发的事情, 使页面"动起来"

比如:用户点击(click)按钮后弹出一个警告窗

事件三要素

  1. 事件源(谁):给谁添加事件,谁可以触发这个事件。

如:点击按钮弹出对话框的事件源是点击的那个按钮。

  1. 事件类型(什么事件):什么事件,事件的触发方式。

    如:点击按钮弹出对话框的事件类型是点击(click)

  2. 事件处理程序(做啥):事件被触发之后所进行的操作,一般通过函数来实现。

如:点击按钮弹出对话框的事件处理程序是弹出对话框这个动作

添加事件步骤

  1. 获取事件源
  2. 注册事件(绑定事件)
  3. 添加事件处理程序(函数)

注册事件/绑定事件

事件触发条件
onclick鼠标点击
onfocus获得鼠标焦点
onblur失去鼠标焦点
onmousemove鼠标移动
onmousedown鼠标按下
onmouseout鼠标离开
onmouseover鼠标经过
onload浏览器已完成页面的加载

传统方法

on开头的事件

    var btn=document.querySelectorAll(".one");
    btn[0].onclick=function(){
        alert("1");
    }
    function fn(){
        alert("2");
    }
    btn[1].onclick=fn;
  • 唯一性
  • 同一个元素同一个事件只能设置一个处理函数,最后注册的处理函数将会覆盖前面注册的处理函数

addEventListener

eventTarget.addEventListener(type,listener[,useCapture])

//type:事件类型字符串,如click,mouseover,不要带on
//listener:事件处理函数
//useCapture:可选参数,默认是 false(冒泡模式)。决定事件流捕获还是冒泡
  • 同一个元素同一个事件可以注册多个监听器,按注册顺序依次执行
    var btn=document.querySelectorAll(".one");
    btn[0].addEventListener("click",function(){
        alert("1");
    })
    function fn(){
        alert("2");
    }
    btn[1].addEventListener("click",fn)

解绑事件/删除事件

传统事件删除方式

eventTarget.onclick = null;

var btn=document.querySelectorAll(".one");
btn[0].onclick=function(){
      alert("1");
      btn[0].onclick=null;
}

removeEventListener()

eventTarget.removeEventListener(type,listener[,useCapture]);

    var btn=document.querySelectorAll(".one");
    function fn(){
        alert("2");
        btn[1].removeEventListener('click',fn);
    }
    btn[1].addEventListener("click",fn)

事件对象

  • event对象代表事件的状态,事件发生后,与事件相关的一系列信息数据的集合都在event对象里面
  • 事件对象是浏览器自动为函数创建的,我们可以改变它的名字,e/event
  • 默认事件是某些元素天生就带有的事件,比如:点击a标签会自动把页面跳转到另一个网页,点击type = "submit"的input标签会把表单提交。某些场景下不希望标签具有默认的功能,需要阻止这种默认功能,也就是阻止默认事件e``.preventDefault();
btn[2].addEventListener("click",function(e){
      e.preventDefault();
})

DOM事件流

事件发生时会在元素节点之间按照特定的顺序传播,这个传播过程即DOM事件流

  • 事件流共有三个阶段:捕获->目标->冒泡
  • JS 代码中只能执行捕获或者冒泡其中的一个阶段。

事件冒泡false

默认执行冒泡

事件源完成事件以后,逐级向上传播到到 DOM 最顶层节点的过程。

事件捕获true

由 DOM 最顶层节点开始,逐级向下传播到事件源。

<body>
    <div class="grandfather">
        <div class="father">
            <div class="son"></div>
        </div>
    </div>
</body>

<script>
var son=document.querySelector(".son");
var father=document.querySelector(".father");
var grandfather=document.querySelector(".grandfather")

son.addEventListener("click",function(){
    alert('son');
},true)

father.addEventListener("click",function(){
    alert('father');
},true)

grandfather.addEventListener("click",function(){
    alert('grandfather');
},true)
</script>
  • onclick 和 attachEvent绑定的事件只能开启冒泡阶段
  • onblur,onfocus,onmouseenter,onmouseleave 没有冒泡阶段

事件委托

多个子元素注册相同的事件时,可以只给父元素绑定这个事件,利用冒泡或捕获影响每个子节点

<body>
    <div class="grandfather">
        <div class="father">
            <div class="son"></div>
        </div>
    </div>
</body>
<script>
var grandfather=document.querySelector(".grandfather")
grandfather.addEventListener("click",function(e){
    e.target.style.backgroundColor = 'red';
})
</script>
<body>
    <ul>
        <li>11111</li>
        <li>22222</li>
        <li>33333</li>
        <li>44444</li>
        <li>55555</li>
    </ul>
    <script>
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) {
            // e.target 可以得到点击的对象
            e.target.style.backgroundColor = 'blue';
        })
    </script>
</body>

定时器

setTimeout()定时器

在经过指定的时间段后调用回调函数,只调用一次

window.setTimeout(调用函数,[延迟的毫秒数]);
  • window可以省略
  • 延迟的毫秒数省略默认是0,注意单位是毫秒
  • 定时器可能有很多,所以经常给定时器赋值一个标识符,用于清除指定的定时器

clearTimeout()停止定时器

clearTimeout()方法取消先前通过调用 setTimeout()建立的定时器

window.clearTimeout(timeoutID)
var btn = document.querySelector('button');
    function fn1(){
        console.log("触发11")
    }
    function fn2(){
        console.log("触发222")
    }
    var timer1=setTimeout(fn1,1000);
    var timer2=setTimeout(fn2,2000);
    btn.addEventListener('click', function() {
        clearTimeout(timer1);
        clearTimeout(timer2);
    })

setInterval()定时器

每隔一段时间,就去调用一次回调函数。调用多次

window.setInterval(回调函数,[间隔的毫秒数]);

clearInterval()停止定时器

window.clearInterval(timeoutID)
var btn = document.querySelector('button');
    function fn1(){
        console.log("触发111")
    }
    function fn2(){
        console.log("触发222")
    }
    var timer1=setInterval(fn1,1000);
    var timer2=setInterval(fn2,2000);
    btn.addEventListener('click', function() {
        clearInterval(timer1);
        clearInterval(timer2);
    })