1.概念
某些元素被执行了某些操作后,触发了某些代码的执行
事件:操作
事件源:元素、组件
监听器:代码
注册监听:将事件、事件源、监听器绑定、当事件源发生了某个事件后,会触发某个监听器的代码
2.常见的事件
2.1点击事件
onclick:点击事件
ondblclick:双击事件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function f1(){
alert(66);
}
function f2(){
var btn2 = document.getElementById("but2");
alert(888);
}
</script>
</head>
<body>
<button onclick="f1()">点击弹一次</button>
<hr />
<button ondblclick="f2()" id="but2">点击弹两次</button>
<
</body>
</html>
2.2鼠标事件
onmouseover:鼠标移动到元素之上
onmousemove:鼠标在元素上移动
onmouseout:鼠标从元素上移开
onmouseup:鼠标松开
onmousedown:鼠标按下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style >
div{
width:100px;
height:100px;
border:1px solid red;
}
</style>
<script type="text/javascript">
onload = function(){
var d = document.getElementById("d");
d.onmousedown = function(){
d.style.background = "pink";
}
d.onmouseup = function(){
d.style.background = "yellow";
}
}
</script>
</head>
<div id="d"></div>
<body>
</body>
</html>
2.3键盘事件
onkeydown:某个键盘按键被按下
onkeyup:某个键盘按键被松开
onkeypress:某个键盘按键按下并松开
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function f(){
alert();
}
</script>
</head>
<input type="button" value="onkeydown" onkeydown="f()" />
<body>
</body>
</html>
2.4焦点事件
onblur:失去焦点
onfocus:获取焦点
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function f1(){
}
function f2(){
}
</script>
</head>
<input type="text"onblur="f1()" onfocus="f2()" style="outline: none;" />
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
onload = function(){
var inp = document.getElementById("inp");
inp.onfocus= function(){
this.style.border = "1px solid blue";
}
inp.onblur = function(){
var value = this.value;
alert(value);
}
}
</script>
</head>
<body>
<input type="text" style="outline: none;" id="inp" />
</body>
</html>
2.5加载事件
window.onload:页面加载完毕后触发,window可以取消
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
onload = function(){
document.getElementsByTagName("button");
for(var i = 0;i <=btns.length;i++){
btns[i].style.background = "red";
}
}
</script>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
</body>
</html>
2.6选择事件
2.7表单事件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function f(){
return false;
}
</script>
</head>
<body>
<form action="https://www.baidu.com" onsubmit="return f()">
<button>跳转</button>
</form>
</body>
</html>