事件绑定
元素节点.on + 事件类型 = 匿名函数
【注】系统会在事件绑定一旦完成的时候,生成一个事件对象
【注】触发事件的时候,系统会自动去调用事件绑定的函数,将事件对象当做第一个参数传入。
条件对象:
button 的属性
0左键
1滚轮
2右键
获取当前鼠标的位置:(原点位置不一样)
clientX clientY 原点位置:可视窗口的左上角为原点
pageX pageY 原点位置:整个页面的左上角(包含滚出去的滚动距离)
screenX screenY 原点位置:电脑屏幕的左上角
举个列子
<script>
document.onmousedown = function(ev){
var e = ev || window.event;
//alert(e.button);
alert(e.clientX + ", " + e.clientY);
alert(e.screenX + ", " + e.screenY);
}
</script>
<body style="height: 3000px;">
<h1>hello world</h1>
</body>
跟随鼠标提示框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/*
事件类型:
mouseover 让提示框显示
mouseout 让提示框隐藏
mousemove 让提示框跟随鼠标去移动
clientX clientY 原点位置:可视窗口的左上角为原点
*/
</script>
<style>
a{display: block;font-size: 40px;margin: 100px;width: 130px;}
#msg{width: 600px;height: 150px;background-color: gray;color: white;display: none;position: absolute;}
</style>
<script>
var arr = [100,122,true,"hello"];
//【注】arr数组中是按照a标签的下标去存储对应的描述信息的
window.onload = function(){
var aAs = document.getElementsByTagName("a");
var oMsg = document.getElementsByTagName("msg");
for(var i = 0; i < aAs.length; i++){
aAs[i].index = i;
aAs[i].onmouseover = function(){
oMsg.innerHTML = arr[this.index];
oMsg.style.display = 'block';
}
aAs[i].onmouseout = function(){
oMsg.style.display = 'none';
}
//添加鼠标移动事件
aAs[i].onmousemove = function(ev){
var e = ev || window.event;
oMsg.style.left = e.clientX + 5 + 'px';
oMsg.style.top = e.clientY + 5 + 'px';
}
}
}
</script>
</head>
<body>
<a href="#">唐太宗</a>
<a href="#">唐高宗</a>
<a href="#">武则天</a>
<a href="#">唐玄宗</a>
<div id="msg"></div>
</body>
</html>
事件对象属性
事件对象的属性:
shiftKey 按下shift键,为true,默认为false
altKey
ctrlKey
metaKey windows系统 按下windows(开始)键,为true
macos系统,按下 command键,为true
[注]和别的操作进行组合,形成一些快捷键操作
<script>
window.onload = function(){
document.onmousedown = function(ev){
var e = ev || window.event;
var arr = [];
if(e.shiftKey){
alert.push("shift");
}
if(e.altKey){
alert.push("alt");
}
if(e.ctrlKey){
arr.push("ctrl");
}
if(e.metaKey){
arr.push("windows");
}
alert(arr);
}
}
</script>
keyCode 键码
which
返回值:键码返回的是大写字母的ASCII码值
格式: var which = e.which || e.keyCode;
[注]只在keydown下支持
<script>
window.onload = function(){
window.onkeydown = function(ev){
var e = ev || window.event;
var which = e.which || e.keyCode;
alert(which);
}
}
</script>
charCode字符码
which
格式: var which = e.which || e.charCode字符码
[注]只在keypress下支持
<script>
window.onload = function(){
window.onkeypress = function(ev){
var e = ev || window.event;
var which = e.which || e.charCode;
alert(which);
}
}
</script>