一.事件监听
1.事件:HTML事件是发生在HTML元素上的
(1).按钮被点击
(2).鼠标被移动到元素上
(3).按下键盘按键
2.事件监听:JavaScript可以在事件被侦测到时执行所对应的代码
二.事件绑定
方式一:通过HTML标签中的事件属性进行绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<input type="buttton" onclick="on()" value="按钮">
</body>
</html>
<script>
function on() {
alert("点击")
}
</script>
方式二:通过DOM元素属性绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<input type="buttton" id="b" value="按钮">
</body>
</html>
<script>
document.getElementById('b').onclick = function () {
alert("点击")
}
</script>
三.常见事件
onclick鼠标单击事件
onblur元素失去焦点
onfocus元素获得焦点
onload某个页面或图像被完成加载
onsubmit当表单提交时触发该事件
onkeydown某个键盘的键被按下
onmouseover鼠标被移到某元素之上
onmouseout鼠标从某元素移开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body onload="load()">
<form action="" style="text-align: center;" onsubmit="submit()">
<input type="text" name="username" onblur="onblur()" onfocus="focus()" onkeydown="keydown()">
<input id="b1" type="submit" value="提交">
<input id="b1" type="button" value="单击事件" onclick="c()">
</form>
<br>
<table width="800px" border="1" cellspacing="0" align="center" onmouseover="mouseover()" onmouseout="mouseout()">
<tr>
<th>学号</th>
<th>姓名</th>
<th>分数</th>
<th>评语</th>
</tr>
<tr align="center">
<td>001</td>
<td>A</td>
<td>100</td>
<td>优秀</td>
</tr>
<tr align="center">
<td>002</td>
<td>B</td>
<td>80</td>
<td>良好</td>
</tr>
</table>
</body>
</html>
<script>
function c() {
alert("鼠标单击")
}
function blur() {
console.log("元素失去焦点")
}
function focus() {
console.log("元素获得焦点")
}
function load() {
alert("加载完成")
}
function submit() {
alert("表单提交")
}
function keydown() {
console.log("键盘的键被按下")
}
function mouseover() {
console.log("鼠标移到元素之上")
}
function mouseout() {
console.log("鼠标从元素之上移开")
}
</script>