event事件对象
1、什么是event事件对象?
用来获取事件的详细信息:鼠标位置、键盘按键等
//获取点击的鼠标位置
document.onclick = function(e){
e.clientx; //获取横坐标
e.clienty; //获取纵坐标
}
事件冒泡
冒泡例子
<!DOCTYPE html>
<html onclick="alert('html');">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body onclick="alert('body');">
<div style="width:300px; height:300px; background:red;" onclick="alert(this.style.background);">
<div style="width:200px; height:200px; background:green;" onclick="alert(this.style.background);">
<div style="width:100px; height:100px; background:#CCC;" onclick="alert(this.style.background);">
</div>
</div>
</div>
</body>
</html>
当点击其中一个div时,会触发所有被点击元素的点击事件,就算元素被覆盖,照样会执行。这就是冒泡事件。
取消冒泡:oEvent.cancelBubble=true
鼠标事件
1、鼠标位置
可视区位置:clientX、clientY(鼠标的坐标)
这里我们注意,现在我们只知道它是鼠标的坐标,但是我们不知道它是鼠标的什么坐标
onmousemove 事件会在鼠标指针移动时发生
键盘事件
onclick=onmousedown+onmouseup;(鼠标点击)
onpress=onkeydown+onkeyup;(键盘按下)
keyCode(键码)
document.onkeydown=function (ev) {
ev.keycode() //获取被点击按键的ascll码
String.fromcharCode(ev.keycode()) // 使用该方法将码转为字符串
}
//ctrlKey、shiftKey、altKey 如果按键为ctrl、shift、alt 则返回true
// ev.ctrlKey
默认行为
使用 return false 可以阻止任意一个事件的默认行为
<script type="text/javascript">
//取消右键菜单
document.oncontextmenu=function () {
return false;
};
</script>
绑定事件
addEventListener
window.onload = function(){
2 var box = document.getElementById("box");
3 box.onclick = function(){
4 console.log("我是box1");
5 }
6 box.onclick = function(){
7 box.style.fontSize = "18px";
8 console.log("我是box2");
9 }
10 }
//只能输出'我是box2',后一个被覆盖
window.onload = function(){
2 var box = document.getElementById("box");
3 box.addEventListener("click",function(){
4 console.log("我是box1");
5 })
6 box.addEventListener("click",function(){
7 console.log("我是box2");
8 })
9 }
//使用addEventListener(),可以将绑定的事件都执行,不会覆盖