javascript事件编程在实际的使用中是比较常见的,本文简单mark一下。主要内容包括:事件处理程序、常用事件、绑定事件方式、事件冒泡、默认行为以及事件对象示例。
1.事件处理程序
事件就是用户或浏览器自身执行的某种动作。比如说click,mouseover,都是事件的名字。而相应某个事件的函数就叫事件处理程序(或事件侦听器)。为事件指定处理程序的方式有好几种,比如行内绑定、动态绑定等。
inlineBinding.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //行内绑定
- function display(){
- alert("Hello");
- alert("Hello");
- alert("Hello");
-
- }
- </script>
- </head>
-
- <body>
- <input type="button" value="确定" onclick="display()"/>
- </body>
- </html>
2.常用的事件
onLoad :页面加载完毕后 一般用于body元素
onUnload :页面关闭后 一般用于body元素
onBlur :失去焦点
onFocus :获得焦点
onClick :点击
onMouseOver :当鼠标经过时
onMouseOut :当鼠标离开时
onMouseDown :当鼠标按下时
onMouseUp :当鼠标抬起时
onMouseMove :当鼠标移动时
onChange :当内容改变时
onSelect :当内容被选中时
onkeypress :当键盘点击时
onkeydown :当键盘按下时
onkeyup :当键盘抬起时
触发顺序:onkeydown、onkeypress、onkeyup
Onkeypress事件无法捕获功能键 代码见下例
onSubmit :当表单提交时
onReset :当表单重置时
inlineBinding2.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //事件处理
- function display(text){
- document.getElementById("div").innerHTML+=text;
-
- }
- </script>
- </head>
-
- <body onload="alert('欢迎!')" onunload="alert('再见')">
- <input type="text" onkeypress="display('press')" onkeydown="display('down')" onkeyup="display('up')"/>
- <div id="div"></div>
- </body>
- </html>
上面的例子体现了onkeypress、onkeydown和onkeyup的使用方法,实际中常用的是onkeyup。
3.绑定事件的方式
3.1行内绑定
<元素 事件=”事件处理程序”>
- <script type="text/javascript">
- function show(){
- alert('hello world!');
- }
- </script>
- <input type="button" value="click me" onclick="show()"/>
上面也可以称为HTML事件处理程序。
这种方式是目前用得比较多的一种,但是在html中指定事件处理程序有两个缺点。
(1)首先:存在一个时差问题。就本例子来说,假设show()函数是在按钮下方,页面的最底部定义的,如果用户在页面解析show()函数之前就单击了按钮,就会引发错误;
(2)第二个缺点是html与javascript代码紧密耦合。如果要更换时间处理程序,就要改动两个地方:html代码和javascript代码。
因此,许多开发人员摒弃html事件处理程序,转而使用javascript指定事件处理程序。
3.2动态绑定
对象.事件=事件处理程序
dynamicBinding.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- window.onload=function(){
- //行内绑定和动态绑定的区别
- document.getElementById("btnok").onclick=function(){
- alert("Hello!");
- };
- document.getElementById("div").onclick=test;
- };
- function test(){
- this.style.color='red';
- }
- </script>
- </head>
-
- <body>
- <input type="button" value="确定" id="btnok"/>
- <div id="div" onclick="test()">javascript</div>
- </body>
- </html>
3.3行内绑定和动态绑定的区别
简单一句话总结,就是行内绑定调用的函数是全局函数和全局变量,即相当于window.方法名和window.变量名,而动态绑定可以将函数的作用域限定在绑定对象的范围内,即可以使用this来引用绑定的对象,比如上例。
4.事件监听
我们能不能为一个dom对象的同一个事件指定多个事件处理程序
4.1如果为一个对象的同一个事件指定多个事件处理程序,那么,后面指定的程序会覆盖前面的。
dynamicBinding3.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- window.onload=function(){
- //为对象的某个时间指定多个事件处理,出现问题。关于事件起泡
- document.getElementById("div1").onclick=test1;
- document.getElementById("div1").onclick=test2;
- };
- function test1(){
- alert("first");
- }
- function test2(){
- alert("second");
- }
- </script>
- </head>
-
- <body>
- <div id="div1">div1</div>
- </body>
- </html>
4.2如果我们想为一个对象的某个事件指定多个事件处理,可以考虑使用事件监听。
事件监听语法:
IE:
attachEvent(type,callback)
type:事件名 如:onclick、onsubmit、onchange等
callback:事件处理程序
基于W3C模型:
addEventListener(type,callback,capture)
Type:事件名 ,没有“on”前缀 如:click、submit、change
Callback:事件处理程序
Capture:事件模型 (可选参数) (冒泡模型、捕捉模型) true:捕捉模型
false:冒泡模型 (默认值)
eventListener.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //使用事件监听解决为对象的某个时间指定多个事件处理
- //注意IE11已经废除了attachEvent方法,想要看到效果需要在兼容模式下运行程序
- //注意此时,会先执行fn2,在执行fn1
- //attachEvent只在IE和基于IE内核的浏览器中是有效的
- //W3C中是使用addEventListener
- function fn1(){
- alert('first');
- }
- function fn2(){
- alert('second');
- }
- window.onload=function(){
- //在IE中使用
- //document.getElementById('div1').attachEvent('onclick',fn1);
- //document.getElementById('div1').attachEvent('onclick',fn2);
- //W3C中
- document.getElementById('div1').addEventListener('click',fn1,false);
- document.getElementById('div1').addEventListener('click',fn2,false);
- };
- </script>
- </head>
-
- <body>
- <div id="div1">div1</div>
- </body>
- </html>
4.3IE和W3C事件监听的不同:
监听方法不同:IE attachEvent 、W3C addEventListener
监听参数不同:IE 没有模型参数、W3C 有模型参数
触发顺序:IE 8及以下的浏览器触发时是先绑定、后触发
W3C浏览器是先绑定、先触发
事件名称不同:IE 事件需要”on”前缀,W3C不需要’on’前缀
4.4解决浏览器兼容性问题
使用
-
- function addEvent(obj,type,callback){
- if(obj.attachEvent){
- obj.attachEvent('on'+type,callback);
- }else{
- obj.addEventListener(type,callback,false);
- }
- }
eventListener2.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //解决浏览器的兼容问题
- function addEvent(obj,type,callback){
- if(obj.attachEvent){//IE
- obj.attachEvent('on'+type,callback);
- }else{//W3C
- obj.addEventListener(type,callback,false);
- }
- }
- function fn1(){
- alert('first');
- }
- function fn2(){
- alert('second');
- }
- window.onload=function(){
- var obj = document.getElementById('div1');
- addEvent(obj,'click',fn1);
- addEvent(obj,'click',fn2);
- };
- </script>
- </head>
-
- <body>
- <div id="div1">div1</div>
- </body>
- </html>
5.事件模型
事件模型分为两种:
1)冒泡模型
2)捕捉模型
5.1事件冒泡是指事件响应时会上水冒一样上升至最顶级元素
bubble.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //出现了事件起泡问题问题
- function fn1(){
- alert('div1');
- }
- function fn2(){
- alert('div2');
- }
- function fn3(){
- alert('div3');
- }
- window.onload=function(){
- document.getElementById("div1").onclick=fn1;
- document.getElementById("div2").onclick=fn2;
- document.getElementById("div3").onclick=fn3;
- };
- </script>
- <style type="text/css">
- #div1{width:400px;height: 400px;background: red;}
- #div2{width:300px;height: 300px;background: green;}
- #div3{width:200px;height: 200px;background: blue;}
- </style>
- </head>
-
- <body>
- <div id="div1">
- <div id="div2">
- <div id="div3"></div>
- </div>
- </div>
- </body>
- </html>
上面的程序,当点击div3时会同时执行div2和div1的点击事件,即事件冒泡
5.2大多数情况下,程序需要对事件冒泡进行取消
取消事件冒泡:
IE:
window.event.cancelBubble=true;
W3C:
function(event){
event.stopPropagation();
}
bubble2.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //大多数情况下,程序需要对事件起泡进行取消
- //解决浏览器兼容问题
- function stopBubble(event){
- //IE下
- if(window.event){
- window.event.cancelBubble=true;
- }else{//W3C下
- event.stopPropagation();
- }
- }
- function fn1(){
- alert('div1');
- }
- function fn2(event){
- alert('div2');
- stopBubble(event);
- }
- function fn3(){
- alert('div3');
- }
- window.onload=function(){
- document.getElementById("div1").onclick=fn1;
- document.getElementById("div2").onclick=fn2;
- document.getElementById("div3").onclick=fn3;
- };
- </script>
- <style type="text/css">
- #div1{width:400px;height: 400px;background: red;}
- #div2{width:300px;height: 300px;background: green;}
- #div3{width:200px;height: 200px;background: blue;}
- </style>
- </head>
-
- <body>
- <div id="div1">
- <div id="div2">
- <div id="div3"></div>
- </div>
- </div>
- </body>
- </html>
上面的程序即取消了点击div2向点击div1的事件冒泡
6.默认行为
有些html元素,有自己的行为,如,提交按钮、超链接
有些时候,我们需要对默认行为进行取消,如表单按钮点击时,用户资料添写不完整,我们这时需要将按钮的默认行为取消。
取消默认行为的方法:
IE:
window.event.returnValue=false;
W3C:
event.preventDefault();
stopDefault.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //阻止表单提交的默认行为
- //解决浏览器兼容问题
- function prevent(event){
- //IE下
- if(window.event){
- window.event.returnValue=false;
- }else{//W3C下
- event.preventDefault();
- }
- }
- window.onload=function(){
- document.getElementById("submit").onclick=function(event){
- if(document.getElementById("username").value==''){
- prevent(event);
- }
- }
- };
- </script>
- <style type="text/css">
- #div1{width:400px;height: 400px;background: red;}
- #div2{width:300px;height: 300px;background: green;}
- #div3{width:200px;height: 200px;background: blue;}
- </style>
- </head>
-
- <body>
- <form action="index.jsp" method="post">
- <input type="text" id="username"/><br>
- <input type="submit" value="提交" id="submit"/>
- </form>
- </body>
- </html>
上面实现了当文本框填写为空时,form不会提交。
7.事件对象
事件对象就是事件发生时系统自动产生的对象,这个对象包含了这个事件发生时所有的信息
如:鼠标移动,那么,鼠标所在的横、纵坐标就保存到了这个事件对象中
获得事件对象:
IE9及以上版本、W3C:
function(event){}
IE8及以下:
window.event
useEvent.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'inlineBinding.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- <script type="text/javascript">
- //通过使用event实现控制div移动
- window.onload=function(){
- var content = document.getElementById("content");
- document.getElementById("text").onkeyup=function(event){
- var code;
- //解决浏览器兼容问题
- //IE下
- if(window.event){
- code = window.event.keyCode;
- }else{//W3C下
- code = event.keyCode;
- }
- switch(code){
- case 37:
- //alert('left');
- content.style.left = (parseInt(content.style.left)-10)+'px';
- break;
- case 38:
- content.style.top = (parseInt(content.style.top)-10)+'px';
- break;
- case 39:
- content.style.left = (parseInt(content.style.left)+10)+'px';
- break;
- case 40:
- content.style.top = (parseInt(content.style.top)+10)+'px';
- break;
-
- }
- };
- };
- </script>
- <style type="text/css">
- #div1{width:400px;height: 400px;background: red;}
- #div2{width:300px;height: 300px;background: green;}
- #div3{width:200px;height: 200px;background: blue;}
- </style>
- </head>
-
- <body>
- <input type="text" id="text"/><br>
- <div id="content" style="width: 100px;height: 100px;background: red;position: absolute;left: 10px;top: 10px;">text</div>
- </body>
- </html>
上面实现了在文本框中移动上、下、左(<-)、右(->)键控制div的移动。
以上即为javascript事件编程的简单介绍,需要在实际的使用过程中仔细体会。