22.8 拖曳任意对象
【实例描述】
网页中可能经常遇到需要拖曳div或table的情况。本例学习一种方法,可实现对任意对象的拖曳。
【实现代码】
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>标题页</title>
<script LANGUAGE="JavaScript">
function DragEvent()
{
//参数
// 开始时的鼠标在对象中的偏移位置
//DargFlag 0:拖曳停止 1:拖曳开始
this.x = 0;
this.y = 0;
this.DragFlag=0;
}
var DragObject = new DragEvent();
function DragMoveObject(obj)
{
if(event.button == 1) //如果按下的是鼠标左键
{
obj.style.position="absolute"; //设置对象为绝对定位模式
if(DragObject.DragFlag==0) //拖曳开始
{
DragObject.DragFlag = 1;
DragObject.x = event.offsetX; //鼠标的x坐标
DragObject.y = event.offsetY; //鼠标的y坐标
}
obj.style.left = event.x-DragObject.x; //保持鼠标在对象中的位置不变
obj.style.top = event.y-DragObject.y;
}
else
{
DragObject.DragFlag = 0; //拖曳停止
}
}
</script>
</head>
<body>
<textarea cols="30" rows="5" onmousedown="DragMoveObject(this);" ></textarea><br />
<input type=button value="拖曳" onmousedown="DragMoveObject(this);" />
<input id="Button1" type="button" value="button"onmousedown="DragMoveObject (this);" />
</body>
</html>
【运行效果】
本例的拖曳效果如图22-8所示。由于没有设置鼠标的形状,所以效果并不明显。

图22-8 本例的拖曳效果
【难点剖析】
本例的重点是捕获鼠标的移动坐标,然后设置指定标签的坐标跟随鼠标的坐标。判断是否按下鼠标使用的条件是“event.button = = 1”。






