您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
javascript学习笔记-事件对象
发布时间:2018-04-05 18:13:33编辑:雪饮阅读()
元素事件被绑定的函数中this指向该元素
即便该函数不是匿名函数而是全局中的函数,因为这里上对其代码的引用,那么代码只要引入到这里了,this自然指向该元素
var box=document.getElementById("box");
box.onclick=function(){
console.log(this);
}
当给一个元素的事件绑定上一个函数,那么浏览器会自动给该函数传递一个参数
该参数是一个事件对象,包含了触发事件后的相关信息。那么我们就可以通过arguments来获取该事件对象
var box=document.getElementById("box");
box.onclick=function(){
console.log(arguments);
};
直接获取事件对象(火狐不支持)
var box=document.getElementById("box");
box.onclick=function(){
alert(window.event);
};
通过一个参数获取事件对象(ie不支持)
var box=document.getElementById("box");
box.onclick=function(xy){
console.log(xy);
};
鼠标事件
只有在主鼠标按钮被单击时(常规一般是鼠标左键)才会触发 click 事件,因此检测按钮 的信息并不是必要的。但对于 mousedown 和 mouseup 事件来说,则在其 event 对象存在一 个 button 属性,表示按下或释放按钮。
火狐、谷歌的左中右button属性分别是0、1、2
ie的左中右button属性分别是1、4、2
document.onmousedown=function(evt){
var e=evt||window.event;
alert(e.button);
}
可视区及屏幕坐标
事件对象提供了两组来获取浏览器坐标的属性,一组是页面可视区(受滚动条影响)左边,另一组是屏幕 坐标。
document.onmousedown=function(evt){
var e=evt||window.event;
alert('可视区域x'+e.clientX + ',可视区域y' + e.clientY);
alert('屏幕x'+e.screenX + ',屏幕y' + e.screenY);
}
按键检测
操作时候按下所要检测的键同时按下鼠标左键
document.onmousedown=function(evt){
var e=evt||window.event;
if(e.shiftKey){alert("你按了shift");}
if(e.ctrlKey){alert("你按了ctrl");}
if(e.altKey){alert("你按了atrl");}
}
获取键码(火狐不兼容)
keyCode 属性的值与 ASCII 码中对应字母
或数字的编码相同。。如果用onkeypress则在火狐中获取值为0
即便是onkeydown在火狐中获取的值也和ie、谷歌有偏差,ie和谷歌是统一的。
document.onkeydown=function(evt){
var e=evt||window.event;
alert(e.keyCode);
}
获取字符编码(ie不支持)
获取字符编码和获取键码其实是一样的。
charCode 属性
这个属性只有在发 生 keypress 事件时才包含值,而且这个值是按下的那个键所代表字符的 ASCII 编码。
同样的在火狐中也是获取值为0。
ie不支持
document.onkeypress=function(evt){
var e=evt||window.event;
alert(e.charCode);
}
获取实际所按字符
document.onkeypress=function(evt){
var e=evt||window.event;
alert(String.fromCharCode(e.keyCode));
}
获取点击元素对象(ie不支持)
document.onclick=function(evt){
var e=evt||window.event;
alert(e.target);
}
获取点击元素对象(火狐不支持)
document.onclick=function(evt){
var e=evt||window.event;
alert(e.srcElement);
}
事件流
事件流是描述的从页面接受事件的顺序,当几个都具有事件的元素层叠在一起的时候, 那么你点击其中一个元素,并不是只有当前被点击的元素会触发事件,而层叠在你点击范围 的所有元素都会触发事件。事件流包括两种模式:冒泡和捕获。
事件冒泡与事件捕获
事件冒泡,是从里往外逐个触发。事件捕获,是从外往里逐个触发。那么现代的浏览器 默认情况下都是冒泡模型,而捕获模式则是早期的 Netscape 默认情况。而现在的浏览器要 使用 DOM2 级模型的事件绑定机制才能手动定义事件流模式。
事件冒泡
window.onload=function(){
document.onclick=function(){
alert("document");
};
document.documentElement.onclick=function(){
alert("html");
};
document.body.onclick=function(){
alert("body");
};
document.getElementById("box").onclick=function(){
alert("box");
};
document.getElementById("inp").onclick=function(){
alert("input");
}
}
事件冒泡的取消
document.getElementById("inp").onclick=function(evt){
alert("input");
var e=evt||window.event;
e.cancelBubble=true;
}
事件冒泡的取消(ie浏览器不支持)
document.getElementById("inp").onclick=function(evt){
alert("input");
var e=evt||window.event;
e.stopPropagation();
}
关键字词:javascript,事件,对象