事件
什么是事件
可以在触发浏览器的行为, 一般用户的各类直接操作就可以被称作事件
常用浏览器事件
window. onblur = function(){ 事件执行的语句} //当窗口失去焦点时
window. onfocus = function(){ 事件执行的语句}//当窗口获得焦点时
window. onload = function(){ 事件执行的语句}//窗口加载完成后
window. onresize = function(){ 事件执行的语句}//窗口大小改变
window. onchange = function(){ 事件执行的语句}//内容改变事件
window. oninput = function(){ 事件执行的语句}//当文本框内容改变时 ,立即将改变内容
window. oninvalid = function(){ 事件执行的语句}//获取表单 未能提交时
window. onselect = function(){ 事件执行的语句}//当文本框内容被选中时
表单事件
表单对象.onsubmit = function(){ 事件执行的语句} //表单绑定提交事件
练习:判断账号密码的正确性 myForm.onsubmit = function () { let userCode = document.getElementById("userCode").value; let userPwd = document.getElementById("userPwd").value; var reg = /^[A-Za-z0-9]{6,12}$/; console.log("触发了表单的提交事件!"); if (userCode == '') { alert("账号不能为空"); } else if (userCode.length < 6 || userCode.length > 12) { alert("账号长度错误"); } else if (!reg.test(userCode)) { alert("账号只能为字母与数字!"); } else if (userPwd == '') { alert("密码不能为空"); } else if (userPwd.length < 6 || userPwd.length > 12) { alert("密码长度错误"); } else if (!reg.test(userPwd)) { alert("密码只能为字母与数字!"); } else { return true; } // return true:可以提交 false 不能提交 return false; }
表单对象.onclick = function(){ 事件执行的语句} //表单绑定单击事件
键盘事件
window.onkeydown = function (event) { event = event || window.event; //解决兼容问题
执行语句
}
//键盘按下事件
window. onkeyup = function (event) { event = event || window.event; //解决兼容问题
执行语句
}
//键盘松开按键事件
window. onkeypress = function (event) { event = event || window.event; //解决兼容问题
执行语句
}
//键盘按下并松开按键事件
练习:控制一个div块在浏览器根据上下左右键移动
var box = document.getElementById("box"); document.onkeydown = function (event) { event = event ||window.event;
<head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0px; padding: 0px; } .divStyle { width: 100px; height: 100px; background: red; position: absolute; } </style> </head> <body> <div id="box" class="divStyle"> </div> </body> <script> var box = document.getElementById("box"); document.onkeydown = function (event) { event = event ||window.event; switch (event.keyCode) { case 37: box.style.left = box.offsetLeft - 10+'px'; break; case 39: box.style.left = box.offsetLeft + 10+'px'; break; case 38: box.style.top = box.offsetTop - 10+'px'; break; case 40: box.style.top = box.offsetTop + 10+'px'; break; } } </script>
鼠标事件
window.onclick = function () { 执行语句 }
//鼠标单击事件
window.οndblclick= function () { 执行语句 }
//鼠标双击事件
window.onmousedown = function () { 执行语句 }
//当鼠标按钮按下运行时
window.onmouseup = function () { 执行语句 }
//当鼠标按钮运行时
window.onmouseover = function () { 执行语句 }
//当鼠标移入时 不能阻止冒泡
window.onmouseout = function () { 执行语句 }
//当鼠标移出时 不能阻止冒泡
window.onmouseenter = function () { 执行语句 }
//当鼠标移出时 可以阻止事件冒泡
window.onmouseleave = function () { 执行语句 }
//当鼠标移出时 可以阻止事件冒泡
window.onmousewheel = function () { 执行语句 }
//当鼠标的滚轮运行