您的位置:首页 > Web前端 > JavaScript

js 实现移动div窗体

2015-09-16 22:18 579 查看
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var x;//鼠标的初始位置
var y;
var ox;//要移动的div对象的位置
var oy;
var flag=false;//判断鼠标此时是否处于按下的状态
function mouse_down(obj){
	obj.style.cursor="move";
	ox=obj.style.left;
	oy=obj.style.top;
	x=window.event.clientX;
	y=window.event.clientY;
	flag=true;	
}
function mouse_move(obj){
	var xx=window.event.clientX;//鼠标现在的位置
	var yy=window.event.clientY;
	if(flag){
		obj.style.left=parseInt(ox)+parseInt(xx)-parseInt(x)+"px";
		obj.style.top=parseInt(oy)+parseInt(yy)-parseInt(y)+"px";
		p1.innerHTML="left:"+obj.style.left+" top:"+obj.style.top;
	}
}
function mouse_up(obj){
	var xx=window.event.clientX;//鼠标现在的位置
	var yy=window.event.clientY;
	if(flag){
		obj.style.left=parseInt(ox)+parseInt(xx)-parseInt(x)+"px";
		obj.style.top=parseInt(oy)+parseInt(yy)-parseInt(y)+"px";
		p2.innerHTML="left:"+obj.style.left+" top:"+obj.style.top;
		
		x=xx;
		y=yy;
		obj.style.cursor="default";
		flag=false;
	}
}
</script>
</head>
<body>
<p id="p1"></p>
<p id="p2"></p>
<div style="background-color:#FF8000;width: 300px;height: 200px;position: absolute;
left: 100px;top:100px;border: 1px solid blue" id="div1" onmousedown="mouse_down(this);" 
onmousemove="mouse_move(this);" onmouseup="mouse_up(this);"></div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: