addEventListener事件监听

1.初步认识

<button id="btn">change Red</button>


<script>
var el=document.querySelector('#btn')
el.addEventListener('click',function(e){
    alert(e)
},false)
</script>

从上面的代码中,我们可以看到addEventListener这个方法有三个参数:
第一个参数是要监听的事件类型,
第二个是事件执行的代码,
第三个是个布尔值。可以不写,默认是false。

2.addEventListener和onclick的区别

<button id="btn1">onclick</button>
<button id="btn2">addEventListener</button>




<script>
var el1=document.querySelector('#btn1')
el1.onclick=function(){
    alert('on-1')
}
el1.onclick=function(){
    alert('on-2')
}

var el2=document.querySelector('#btn2')
el2.addEventListener('click',function(){
    alert('add-1')
},false)
el2.addEventListener('click',function(){
    alert('add-2')
},false)
</script>

运行上述代码,可以发现onclick只能执行一遍,只弹出了‘on-2’
而addEventListener,弹框出现了两遍,‘add-1’,‘add-2’分别都弹出了

3.关于addElementListener最后一个参数的讲解

<style>
    #box{
      width: 300px;
      height: 300px;
      background-color: blue;
    }
    #big{
      width: 900px;
      height: 900px;
      background-color:red;
    }
  </style>




<body id="body">
   <div id="big">
  <div id="box"></div>
</div>
</body>





<script>
var elbox=document.querySelector('#box')
elbox.addEventListener('click',function(){
    alert('box')
    console.log('box')

},true)


var elbig=document.querySelector('#big')
elbig.addEventListener('click',function(){
    alert('big')
},false)


var elbody=document.querySelector('#body')
elbody.addEventListener('click',function(){
    alert('body')
},false)
</script>

当最后一个值是true的时候:你会发现点击盒子时是从“body”开始的,说明它是从document开始解析的
当最后一个值是false的时候:你会发现点击盒子时是从当前盒子开始弹出弹框的

true -- (事件捕捉event capturing)—— 从最外面找到指定元素
false -- (事件冒泡event Bubbling)——从当前元素向外扩散

4 中止冒泡event.stopPropagation()

<style>
    #box{
      width: 300px;
      height: 300px;
      background-color: blue;
    }
    #big{
      width: 900px;
      height: 900px;
      background-color:red;
    }
  </style>




<body id="body">
   <div id="big">
  <div id="box"></div>
</div>
</body>





<script>
//在这段加入语句加入e.stopPropagation()
var elbox=document.querySelector('#box')
elbox.addEventListener('click',function(e){
e.stopPropagation()
    alert('box')
    console.log('box')

},false)


var elbig=document.querySelector('#big')
elbig.addEventListener('click',function(){
    alert('big')
},false)


var elbody=document.querySelector('#body')
elbody.addEventListener('click',function(e){
e.stopPropagation()
    alert('body')
},false)
</script>

执行上述语句我们可以看到,我们在点击class为‘box’这个div的时候,只弹出了一个弹框,没有弹出多余的弹框。
同样,这条语句也是用true 的条件下。

5.取消预设行为e.prentDefault

  <a style="display: block;" href="http://www.baidu.com" id="baidu">百度</a>



<script>
elBaidu.addEventListener('click',function(e){
console.log(e);
e.preventDefault();
})
</script>

执行此代码你会发现,a链接没有跳转到百度页面,而且页面一直也没有动。同样使用a链接是空链接的时候。也适用于其他元素。
使用了e.preventDefault()取消浏览器的预设行为。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。