Javascript事件驱动编程

Javascript事件驱动编程

基本概述

    JS是采用事件驱动的机制来响应用户操作的,也就是说当用户对某个html元素进行操作的时候,会产生一个时间,该时间会驱动某些函数来处理。

PS:这种方式和Java GUI中的事件监听机制很像,都是需要注册监听,然后再处理监听,只不过实现的方式不同而已。

 

可以参考w3school文档:

http://www.w3school.com.cn/jsref/dom_obj_event.asp

http://www.w3school.com.cn/tags/html_ref_eventattributes.asp


事件驱动原理

事件源:产生事件的地方(html元素)

事件:点击/鼠标操作/键盘操作等等

事件对象:当某个事件发生时,可能会产生一个事件对象,该事件对象会封装好该事件的信息,传递给事件处理程序

事件处理程序:响应用户事件的代码


案例:

<html>
	<head>
		<script type="text/javascript">
			function test1(e){
				window.alert("x=" + e.clientX + " y=" + e.clientY);
			}
			function test2(e){
				window.alert("x=" + e.clientX + " y=" + e.clientY);
			}
			function test3(e){
				window.alert(new Date().toLocaleString());
			}
			function test4(e){
				if(e.value == "red"){
					div1.style.backgroundColor = "red";
				} else if (e.value == "black"){
					div1.style.backgroundColor = "black";
				}
			}
		</script>
	</head>
	<body>
		<input type="button" οnclick="test1(event)" value="button1">
		<input type="button" οnmοuseοver="test2(event)" value="button2">
		<input type="button" οnclick="test3(event)" value="button3">
		<div id="div1" style="width: 400px; height: 300px; background-color: red"></div>
		<input type="button" οnclick="test4(this)" value="red">
		<input type="button" οnclick="test4(this)" value="black">
	</body>
</html>


事件编程操作分析

           ①确定事件并为其绑定一个函数

           ②书写绑定的函数

           ③处理数据

JS事件分类

鼠标事件 

click dblclick mousedown mouseout mouseover mouseup mousemove等

键盘事件 

keydown keypress keyup等

HTML事件 

window的onload unload error abort 文本框的select change等

其他事件

页面中有些特殊对象运行过程中产生的事件

 

案例1:监听鼠标点击事件,并能够显示鼠标点击的位置x,y

<html>
     <head>
     <script>
     function test1(e){
         window.alert("x="+e.clientX+"y="+e.clientY);
     }
     </script>
     </head>
     <body οnmοusedοwn="test1(event)">
     </body>
</html>

点击浏览器之后,显示坐标(有些浏览器可能无效)


案例2:点击按钮,图片变成红色,黑色

方法:JS访问内部css

//js如何访问css属性,来改变外观
<html>
    <head>
    <script>
        function test3(e){
           var pic=document.getElementById("pic");
           if(e.value=="红色"){
               pic.style.backgroundColor="red";
           }
           else if(e.value=="黑色"){
                pic.style.backgroundColor="black";
            }
      }
    </script>
    </head>
    <body >
        <div id="pic" style="border:1;background-color:red;width:300px;height:300px"></div>
        <input type="button" οnclick="test3(this)" value="红色">
        <input type="button" οnclick="test3(this)" value="黑色">
    </body>
</html>

方法:JS访问外部css(这方法不一定适用于所有浏览器)

event2.css

.style {
    border:1;
    background-color:red;
    width:300px;
    height:300px;
}

event2.html

<html>
    <head>
    <script>
        function test3(e){
            //取连接的第一个css文件的内容用0
            var ocssRules=document.styleSheets[0].rules;
            //从ocssRules取出你希望的样式
            var style=ocssRules[0];//这里面的0表示event2.css文件中第一个规则
            if(e.value=="黑色"){
                style.style.backgroundColor="black";
             }
             else if(e.value=="红色"){
                 style.style.backgroundColor="red";
             }
        }
    </script>
    </head>
    <body>
        <div class="style"></div>
        <input type="button" οnclick="test3(this)" value="红色">
        <input type="button" οnclick="test3(this)" value="黑色">
      </body>
</html>

案例3区分当前浏览器的内核是什么?(区分出ie6/7/8/  火狐等)

<script language="javascript">
     if(window.XMLHttpRequest)
     { //Mozilla, Safari, IE7,IE8  
    	  	if(!window.ActiveXObject)
        {	 // Mozilla, Safari,  
         	alert('Mozilla, Safari');  
     	}
         else
         {  
         	alert('IE7 .8');  
     	}  
 	  }
      else 
      {  
     	 alert('IE6');  
 	  } 
</script>

案例4一个事件可以被多个函数监听

<html>
    <head>
    function test(e){
        window.alert("fss");
    }
    function test1(e){
        window.alert("sfdsdf");
    }
    </script>
    </head>
    <body>
        <div class="style"></div>
        <input type="button" οnclick="test(this),test1(this)" value="红色">
    </body>
</html>

案例5:防止用户通过点击鼠标右键菜单拷贝网页内容,选择网页内容

<html>
	<script type="text/javascript">
		function test(){
		    //window.alert("没有菜单");
		    return false;
	    }
	    function test2(){
		    //window.alert("全选不行");
		    return false;
	    }	
    </script> 
    </head> 
    <!--body元素响应oncontextmenu,onselectstart事件 -->
    <body οncοntextmenu="return test()" onselectstart="return test2()"> 	
	    内容
    </body>
</html>


综合案例:简单的计算器
<html>
	<head>
		<script>
			function calc(event){
				// test 
				//window.alert(event.value);
				var val = new String(event.value);
				// clear space
				val = val.trim();
				var res = document.getElementById("res");
				// clear
				if(val == "clear"){
					res.value = "";
				}

				// back
				if(val == "back"){
					res.value = res.value.substring(0, res.value.length - 1);
				}

				//  power
				if(val == "power"){
					val = "p";
				}
				// add val to text
				if(val.length == 1 && val != "="){
					res.value = res.value + val;
				}
 
				// calc result
				if(val == "="){
					var arr;
					var result;
					// power
					if(res.value.indexOf("p") != -1){
						arr = res.value.split("p");
						//window.alert(arr);
						 result = Math.pow(parseFloat(arr[0]) ,parseFloat(arr[1]));
						//window.alert(res);
						res.value = result;
					} 			
					// plus
					if(res.value.indexOf("+") != -1){
						arr = res.value.split("+");
						//window.alert(arr);
						 result = parseFloat(arr[0]) + parseFloat(arr[1]);
						//window.alert(res);
						res.value = result;
					} else if(res.value.indexOf("-") != -1){
						// minus
						arr = res.value.split("-");
						//window.alert(arr);
						result = parseFloat(arr[0]) - parseFloat(arr[1]);
						//window.alert(res);
						res.value = result;
					} else if(res.value.indexOf("*") != -1){
						// multiply
						arr = res.value.split("*");
						//window.alert(arr);
						result = parseFloat(arr[0]) * parseFloat(arr[1]);
						//window.alert(res);
						res.value = result;
					} else if(res.value.indexOf("/") != -1){
						// division
						arr = res.value.split("/");
						//window.alert(arr);
						result = parseFloat(arr[0]) / parseFloat(arr[1]);
						//window.alert(res);
						res.value = result;
					} else if(res.value.indexOf("%") != -1){
						// module
						arr = res.value.split("%");
						//window.alert(arr);
						result = parseFloat(arr[0]) % parseFloat(arr[1]);
						//window.alert(res);
						res.value = result;
					}
				}	
			}
		</script>
	</head>
	<body>
		<table border="1px" cellpadding="10px" cellspacing="5px" align="center">
			<tr align="center">
				<td colspan="4"><input type="text" id="res" size="35px" value="" style="text-align:right;"/></td>
			</tr>
			<tr align="center">
				<td><input type="button" value="power" οnclick="calc(this)"/></td>
				<td><input type="button" value="clear" οnclick="calc(this)"/></td>
				<td colspan="2"><input type="button" value="      back      " οnclick="calc(this)"/></td>
			</tr>
			<tr align="center">
				<td><input type="button" value="   1   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   2   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   3   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   +   " οnclick="calc(this)"/></td>
			</tr>
			<tr align="center">
				<td><input type="button" value="   4   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   5   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   6   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   -    " οnclick="calc(this)"/></td>
			</tr>
			<tr align="center">
				<td><input type="button" value="   7   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   8   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   9   " οnclick="calc(this)"/></td>
				<td><input type="button" value="   *   " οnclick="calc(this)"/></td>
			</tr>
			<tr align="center">
				<td><input type="button" value="   0    " οnclick="calc(this)"/></td>
				<td><input type="button" value="   =    " οnclick="calc(this)"/></td>
				<td><input type="button" value="   %    " οnclick="calc(this)"/></td>
				<td><input type="button" value="   /    " οnclick="calc(this)"/></td>
			</tr>
		</table>
	</body>
</html>


综合案例:表格隔行换色+高亮显示

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>表格隔行换色</title>
		<script type="text/javascript">
               function $(id) {
	             return document.getElementById(id);
               }
               function $name(name) {
	             return document.getElementsByName(name);
               }
			window.onload = function () {
				var vRows =  $("tab1").tBodies[0].rows;
				// alert(vRows.length);
				for(var i = 0; i < vRows.length; i++) {
					// 高亮显示
					vRows[i].onmouseover = function() {
						// alert("over");
						// 设置属性和直接赋值有什么区别
						//this.backGroundAttr = this.style.backgroundColor;
						this.setAttribute("bgc", this.style.backgroundColor);
						// alert(this.backGroundAttr);
						this.style.backgroundColor = "red";
					};
					vRows[i].onmouseout = function() {
						// alert("out");
						// this.style.backgroundColor = this.backGroundAttr;
						this.style.backgroundColor = this.getAttribute("bgc")
					};
					// 隔行变色
					if(i % 2 == 0) {
						vRows[i].style.backgroundColor = "gray";
					} else {
						vRows[i].style.backgroundColor = "lightgray";
					}
				}
			};
		</script>
	</head>
	<body>
		<table border="1" width="500" height="50" align="center" id="tab1">
			<thead>
				<tr>
					<th>编号</th>
					<th>姓名</th>
					<th>年龄</th>
				</tr>
			</thead>
			<tbody>
				<tr >
					<td>1</td>
					<td>张三</td>
					<td>22</td>
				</tr>
				<tr >
					<td>2</td>
					<td>李四</td>
					<td>25</td>
				</tr>
				<tr >
					<td>3</td>
					<td>王五</td>
					<td>27</td>
				</tr>
				<tr >
					<td>4</td>
					<td>赵六</td>
					<td>29</td>
				</tr>
				<tr >
					<td>5</td>
					<td>田七</td>
					<td>30</td>
				</tr>
				<tr >
					<td>6</td>
					<td>汾九</td>
					<td>20</td>
				</tr>
			</tbody>
		</table>
	</body>
</html>

综合案例:省市二级联动

<select name="province" id="province" οnchange="chooseCity(this.value)">
    <option selected="selected" disabled="disabled">---请选择您的省份---</option>
    <option value="0">湖南</option>
    <option value="1">湖北</option>
    <option value="2">广东</option>
</select>
<select name="city" id="city">
    <option selected="selected" disabled="disabled">---请选择您的城市---</option>
</select>

var cities = new Array(3);
cities[0] = new Array("长沙市","株洲市","湘潭市","衡阳市","邵阳市","岳阳市","常德市","张家界市","益阳市","郴州市","永州市","怀化市","娄底市","湘西土家族苗族自治州");
cities[1] = new Array("武汉市","黄石市","十堰市","宜昌市","襄樊市","鄂州市","荆门市","孝感市","荆州市","黄冈市","咸宁市","随州市","恩施土家族苗族自治州","仙桃市","潜江市","天门市","神农架林区");
cities[2] = new Array("广州市","韶关市","深圳市","珠海市","汕头市","佛山市","江门市","湛江市","茂名市","肇庆市","惠州市","梅州市","汕尾市","河源市","阳江市","清远市","东莞市","中山市","潮州市","揭阳市","云浮市");

function $(id) {
	return document.getElementById(id);
}
// 省市二级联动
function chooseCity(val) {
	// 获取id为city的结点
	var cityEle = $("city");
	// 初始化方法
	// 1.选项设置为0
	// cityEle.options = 0;
	// 2.删除所有子结点
	for (var i = 0; i < cityEle.childNodes.length;) {
		// 删除时,数组会自动变小,所以无需自增
		// window.alert(cityEle.childNodes.length);
		cityEle.removeChild(cityEle.childNodes[i]);
	}
	
	for(var i = 0; i < cities[val].length; i++) {
		var cityText = document.createTextNode(cities[val][i]);
		var cityNode = document.createElement("option");
		var cityAttr = document.createAttribute("value");
		cityAttr.value = i;
		cityNode.setAttributeNode(cityAttr);
		cityNode.appendChild(cityText);
		cityEle.appendChild(cityNode);
	}
}



常用事件总结

           onsubmit:一般用在表单提交上面,书写的位置在<form>标签里面,而且必须要有返回值

           onload:页面加载的时候使用,绑定的时候写在<body>标签里面,只写一个即可。

          

           onclick:需要使用鼠标进行单击的地方,需要操作哪个元素就绑定到那个元素上面去。

           onfocus:当光标移动到某个地方的时候使用,需要操作哪个元素就绑定到那个元素上面去。

           onblur:当光标移离开某个地方的时候使用,需要操作哪个元素就绑定到那个元素上面去。

           onchange:当用户改变域的内容的时候使用改事件(省市二级联动),需要操作哪个元素就绑定到那个元素上面去。

           ondblclick:鼠标双击某个对象 ,需要操作哪个元素就绑定到那个元素上面去。

          

           onkeydown某个键盘的键被按下,需要操作哪个元素就绑定到那个元素上面去。

           onkeypress某个键盘的键被按下或按住,需要操作哪个元素就绑定到那个元素上面去。

           onkeyup某个键盘的键被松开,需要操作哪个元素就绑定到那个元素上面去。

           上面三个事件一般都是连续使用。用在搜索功能上面!

 

           onmouseover鼠标被移到某元素之,需要操作哪个元素就绑定到那个元素上面去。

           onmousemove鼠标被移动 ,需要操作哪个元素就绑定到那个元素上面去。

           onmouseout鼠标从某元素移开,需要操作哪个元素就绑定到那个元素上面去。


PSJavaScript中的事件并不止这么一点,用到时查文档就行了,可以用上面给的w3school的文档或者是用《JavaScript权威指南》第6896页及以后的事件处理程序有关内容。

PS:HTML的文档加载顺序是由上至下的,所以如果将JavaScript脚本写在前面的话,那么有时候因为其访问对象还没加载入浏览器引擎中,而导致无法访问到对应对象,所以建议将脚本<script>元素写至body的最后连续几个子元素,这样是绝对不会出现访问出错问题的。

PS:当然也可以通过将语句放入onload加载事件中加载,也可以通过在<script>元素上加上refer属性延迟加载。但是最方便、最直接的还是放在html文档尾部。

 

----------参考《韩顺平.轻松搞定网页设计(html+css+js)》


  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值