事件触发时 handler函数内部会接收数据 触发时的信息
打印所有事件指标
var box=document.querySelector(".box")
box.addEventListener("click",function(e){
console.log(e); //所有事件指标
})
e:事件指标
e.pageX,e.pageY 表示整个页面的坐标
e.KeyCode 表示键盘上按下的键 用数字形式表示
e.offsetX,e.offsetY 表示当前元素本身的坐标
e.movementX 鼠标上,右移动为整数 左下负数
代码示例:
document.body.appendChild(box)
box.addEventListener("click",function(e){
console.log(e.pageX,e.pageY); //整个页面的哪个位置
})
box.addEventListener("click",function(e){
console.log(e.offsetX,e.offsetY); //元素本身的哪个位置
})
box.onmousemove=function(e){
console.log(111,e.movementX);//movementX 鼠标上,右移动为整数 左下负数
}
对于以下代码:
button有一个行内绑定onlick事件
1.当直接写出btn2.onlick=fucntion(e){} 时 e打印为 pointevent{} 打印this指向button标签
2.直接写函数function fn(e){e,this} 此时e打印button this打印window
3.使用监听事件传参e btn2.addEventListener("click",function(e){e,this} e打印pointevent this指向button
4.改用箭头函数fn=(e)=>{e,this} e打印button this指向window
5.监听事件箭头函数 e打印事件对象 this打印window
<button id="btn2" onclick="fn(this)">btn2</button>
btn2.onclick=function(e){
console.log(e,this);
}
function fn(e,e2){
// console.log(e,window.event);
// e.is(PointerEvent)//检查e是不是这个类型
e=(e.constructor(PointerEvent)&&e)||window.event//兼容写法
console.log(e);
}
function fn(e){
console.log(e,this);//e打印button this打印window
}
btn2.addEventListener("click",function(e){
console.log(e,this);// e打印事件对象 this指向button
})
// 改成箭头函数都打印window
fn=(e)=>{
console.log(e,this);//e打印button this打印window
}
btn2.addEventListener("click",(e)=>{ //e打印事件对象 this打印window
console.log(e,this);
})