Event对象(二)

1、默认行为

什么是默认行为?不需要我们编写,浏览器自带的功能,就是默认行为。像右键菜单。

有时候我们需要阻止默认行为:return false; 例如,阻止右键菜单:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
	<title>阻止右键菜单</title>
</head>
<body>
	
</body>
</html>
<script type="text/javascript">
document.oncontextmenu = function(){
	return false;
}
</script>

2、拖拽

原理:通过鼠标与DIV左上角的距离来判断。用到的事件:onmousedown(存储距离),onmousemove(根据距离,计算DIV最新的位置),onmouseup(清空onmousemove和onmouseup)。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
	<title>拖拽</title>
	<style type="text/css">
	#div1{width:100px;height:100px;background:red;position:absolute;}
	</style>
</head>
<body>
	<div id="div1"></div>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
	var oDiv = document.getElementById('div1');
	var disX = disY = 0;	//存储鼠标与div左上角的距离;
	
	oDiv.onmousedown = function(e){
		var oEvent = e || event;
		
		disX = oEvent.clientX - this.offsetLeft;
		disY = oEvent.clientY - this.offsetTop;
		
		document.onmousemove = function(e){
			var oEvent = e || event;
			var left = oEvent.clientX - disX;
			var top = oEvent.clientY - disY
			
			if(left < 0){
				left = 0;
			}else if(left > document.documentElement.clientWidth - oDiv.offsetWidth){
				left = document.documentElement.clientWidth - oDiv.offsetWidth;
			}
			if(top < 0){
				top = 0;
			}else if(top > document.documentElement.clientHeight - oDiv.offsetHeight){
				top = document.documentElement.clientHeight - oDiv.offsetHeight;
			}
			oDiv.style.left = left + 'px';
			oDiv.style.top = top + 'px';
		}
		
		document.onmouseup = function(){
			this.onmousemove = null;
			this.onmouseup = null;
		}
		
		return false;
	}
}
</script>


PS:博客搬家了,以后不再 CSDN 更新了,见谅。最新博客地址:http://www.cnblogs.com/yjzhu/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值