目录
1.onclick事件
onclick 事件会在元素被点击时发生。
代码示例:
<!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, initialscale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="demo()">点我⼀下</button>
</body>
<script>
function demo(){
alert("哎呦!我被单击了~~");
}
</script>
</html>
运行结果:
2.onmouseover事件和onmouseout事件
onmouseover 事件是指⿏标移动到指定元素上⽅时触发的事件
onmouseout 事件是⿏标从元素上离开时触发
代码示例:
<!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, initialscale=1.0">
<title>Document</title>
</head>
<body>
<div style="background-color: palegreen;" onmouseover="demo01()" onmouseout="demo02()">学习js事件</div>
</body>
<script>
// onmouseover事件
function demo01(){
alert("鼠标移动到div上了");
}
// onmouseout事件
function demo02(){
alert("鼠标离开div了");
}
</script>
</html>
运行结果:
3.onblur事件和onfocus事件
onblur 当前元素失去焦点时触发此事件
onfocus 当某个元素获得焦点时触发此事件
示例代码:
<!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, initialscale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" onblur="demo04()" onfocus="demo05()">
</body>
<script>
// onblur事件
function demo04(){
alert("文本框失去焦点");
}
// onfocus事件
function demo05(){
alert("文本框获得焦点");
}
</script>
</html>
4. onreset事件和onsubmit事件
onreset 当点击表单中的重置按钮时触发此事件
onsubmit 当提交表单时触发此事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="form1" action="">
<input type="text" name="username" placeholder="请输入用户名">
<button type="submit" name="doSubmit">提交</button>
<button type="reset" name="soReset">重置</button>
</form>
<script type="text/javascript">
var f = document.getElementById('form1');
f.onsubmit = function(){
if(this.username.value == ''){
alert('请输入用户名');
return false;
}
}
f.onreset = function(){
return confirm('你确定要重置?');
}
</script>
</body>
</html>
5.onchange事件
onchange 事件表示在域的内容被改变时触发的事件
示例代码:
<!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, initialscale=1.0">
<title>Document</title>
</head>
<body>
搜索:<input type="search" onchange="demo03()">
</body>
<script>
// onchange事件
function demo03(){
console.log("搜索框的内容被改变了");
}
</script>
</html>
运行结果: