事件对象
由于标准DOM和IE-DOM所提供的事件对象的方法有所不同,导致使用JavaScript在不同的浏览器中获取事件对象比较繁琐。jQuery针对该问题进行了必要的封装与扩展,已解决浏览器兼容性问题,使得在任意浏览器中都可以轻松获取事件处理对象。
事件对象常见的属性列表:
属性 | 描述 |
---|---|
pageX | 鼠标指针相对于文档的左边缘的位置 |
pageY | 鼠标指针相对于文档的上边缘的位置 |
target | 返回触发事件的元素 |
type | 返回时间的类型 |
which | 返回在鼠标或键盘事件中被按下的键 |
data | 用于传递事件之外的额外参数 |
事件对象常用的方法列表:
方法 | 描述 |
---|---|
preventDefault() | 阻止元素发生默认的行为(例如,当单击提交按钮时阻止表单提交) |
stopPropagation() | 阻止事件的冒泡 |
isDefaultPrevented() | 根据事件对象中是否调用过isDefaultPrevented()返回一个布尔值 |
isPropagetionStopped() | 根据事件对象中是否调用过isPropagetionStopped()返回一个布尔值 |
示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery基本操作事件对象</title>
<script type="text/javascript" src="js/jquery-1.x.js"> </script>
<style type="text/css">
div{margin-top:4px;}
#middleDiv,#rightDiv{width:200px;height:100px; background-color:#CCC; display:inline-block;}
</style>
</head>
<body>
<div id="leftDiv">
<form action="http://www.itshixun.com">
用户名:<input type="text" id="userName"/>
<div id="innerDiv">
<input type="submit" value="普通提交按钮" id="submitBtn"/>
<input type="submit" value="阻止默认按钮" id="stopSubmitBtn"/>
<input type="button" value="普通按钮" id="normalBtn"/>
<input type="button" value="阻止冒泡按钮" id="stopPropagateBtn"/>
</div>
</form>
</div>
<div id="middleDiv"></div>
<div id="rightDiv"></div>
<script type="text/javascript">
$(function(){
//提交按钮,默认提交表单
$("#submitBtn").on("click",function(event){
console.log("点击'普通提交按钮'");
});
//使用preventDefault()方法阻止元素的默认行为(如表单提交、超链接等)
//但事件会继续向外传递
$("#stopSubmitBtn").on("click",function(event){
console.log("点击'阻止默认按钮',阻止默认元素的默认行为(如表单提交等)");
event.preventDefault();
});
//普通按钮,具有事件冒泡行为
$("#normalBtn").on("click",function(event){
console.log("点击'普通按钮'");
});
//普通按钮,并阻止冒泡行为
$("#stopPropagateBtn").on("click",function(event){
console.log("点击'阻止冒泡按钮',阻止事件的冒泡行为");
event.stopPropagation();
});
//用于接收内部按钮传递来的冒泡事件
$("#innerDiv").on("click",printEvent);
//鼠标移动时,获取鼠标的相对坐标
$("#middleDiv").on("mousemove",function(event){
var x=parseInt(event.pageX-$(this).offset().left);
var y=parseInt(event.pageY-$(this).offset().top);
$(this).html("鼠标位置:"+x+","+y);
});
//鼠标点击判断处理
$("#rightDiv").on("mousedown",{user:'jCuckoo'},function(event){
if(event.which==1){
$("#rightDiv").html(event.data.user+"点击了鼠标左键").css("background-color","#FFC");
}else if(event.which==2){
$("#rightDiv").html(event.data.user+"点击了鼠标中键").css("background-color","#FF6");
}else if(event.which==3){
$("#rightDiv").html(event.data.user+"点击了鼠标右键").css("background-color","#FC0");
}
});
});
//定义一个处理事件的函数
function printEvent(event){
var result="事件源:"+event.target.value;
result+=" 事件类型:"+event.type;
result+=" 当前标签类型:"+$(this).get(0).tagName;
console.log(result);
}
</script>
</body>
</html>