JS-48 Event事件对象

一、Event事件对象:事件发生以后,会产生一个事件对象,作为参数传给监听函数。

Event对象属性:Event.Target、Event.type

1、Event.target

  Event.target属性返回事件当前所在的节点

  //HTML代码为

  //<p id="para">hello</p>

  function setColor(e){

  console.log(this===e.target);

  e.target.style.color='red';

  }

  para.addEventListener('click',setColor);

 

 

2、Event.type

 Even.type属性返回一个字符串,表示事件类型。事件的类型是在生成事件的时候。该属性只读

二、Event对象方法:Event.preventDefault()、Event.stopPropagation()

1、Event.preventDefault

  Event.preventDefault方法取消浏览器对当前事件的默认行为。比如点击连接后,浏览器默认会跳转到另一个页面,使用这个方法后,就不会跳转了

  btn.onclick=function(e){

  e.preventDefault();//阻止默认事件

  console.log("点击A标签");

  }

2、Event.stopPropagation()

  stopPropagation方法阻止事件在DOM中继续传播,防止在接触发定义在别的节点上的监听函数,但是不包括在当前节点上其他的事件监听函数

  btn.onclik=function(e){

  e.stopPropaation();//阻止事件冒泡

  console.log("btn");

  }

 

 3、Event.stopPropation()

  stopPropagation方法阻止事件在DOM中继续传播,防止在触发定义在别的节点上的监听函数,但是不包括在当前节点上其他的事件监听函数

  btn.onclik=function(e){

  e.stopPropagation();//阻止事件冒泡

  console.log("btn");

  }

 

 

 

  

  

 

 

 

  

 

 

  

posted @ 2025-02-05 17:52  张筱菓  阅读(16)  评论(0)    收藏  举报