jQuery事件对象

125 阅读1分钟
  • jQuery事件对象其实就是js事件对象的一个封装,处理了兼容性。
  • jQuery中事件用参数e来获取 例如:
		$("#btn").on("click",function(e){
			console.log(e);//[object Object]
		});
  • screenX和screenY。对应屏幕最左上角的值
  • clientX和clientY。距离页面(可视区)左上角的位置(忽视滚动条)
  • pageX和pageY。距离页面最顶部的左上角的位置(会计算滚动条的距离)

event.stopPropagation() 阻止事件冒泡行为

事件冒泡:子元素事件触发完,可能会引起父元素相同事件的触发

		$("#btn").on("click",function(e){
			alert(btn的单击事件);
			e.stopPropagation();
		});

e.stopPropagation();会阻止单击btn时触发父元素的单击事件。

event.preventDefault() 阻止浏览器默认行为

比如a标签的跳转行为

		$("a").click(function(e){
			alert("a的单击事件");
			e.preventDefault();
		});

return false : 既能阻止事件冒泡,又能阻止浏览器默认行为。

event.keyCode 按下的键盘代码

例如:

		$(document).on("keydown",function(e){
			//输出按下键的ASCII码
			console.log(e.keyCode);
		});

按键改变颜色练习:

1.png

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#bgChange{
				height: 200px;
				width: 200px;
				background-color: gold;
				font-size: 20px;
				padding: 10px;
			}
		</style>
	</head>
	<body>
		<div class="wrap">
			<h1>按键改变颜色</h1>
			<div id="bgChange">
				keyCode为:
				<span id="keyCodeSpan"></span>
			</div>
		</div>
	</body>
</html>
<script type="text/javascript" src="js/jquery.js" ></script>
<script>
	$(function(){
		var $div=$("#bgChange");
		var $showCode=$("#keyCodeSpan");
		$(document).on("keydown",function(e){
			//r:82 g:71 b:66 p:80 y:89
			switch(e.keyCode){
				case 82:
				  $div.css("background-color","red");
				  $showCode.text(82);
				break;
				
				case 71:
				  $div.css("background-color","green");
				  $showCode.text(71);
				break;
				
				case 66:
				  $div.css("background-color","blue");
				  $showCode.text(66);
				break;
				
				case 80:
				  $div.css("background-color","purple");
				  $showCode.text(82);
				break;
				
				case 89:
				  $div.css("background-color","yellow");
				  $showCode.text(89);
				break;
				
				default:
				  $div.css("background-color","gold");
				  $showCode.text("其他");
			}
		});
	});
</script>