<%@ 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>js 实现移动div窗体
最新推荐文章于 2022-09-22 16:22:41 发布
本文介绍了一个使用JavaScript实现的拖动HTML页面中DIV元素的方法。通过监听鼠标按下、移动及释放事件,可以任意调整指定DIV元素的位置。
1万+

被折叠的 条评论
为什么被折叠?



