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:博客搬家了,以后不再 优快云 更新了,见谅。最新博客地址:http://www.cnblogs.com/yjzhu/