网页上实现拖拽其实也不是很复杂.第一你需要知道鼠标坐标,第二你需要知道用户鼠标点击一个网页元素并实现拖拽,最后我们要实现移动这个元素.
请看下面的代码:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=gb2312" />
<meta name="generator" content="editplus2.21" />
<meta name="author" content="jiucai" />
<meta name="keywords" content="jiucai" />
<meta name="description" content="jiucai" />
<title>拖动层测试</title>
<style type="text/css">
body { font-size:9pt;}
table {border-collapse: collapse; border: 1px #6699FF solid;}
td { border: 1px #6699FF solid;}
.drag{
position:relative;
cursor:pointer;
z-index: 100;
border: #669999 1px solid;
width: 150px;
margin: 5px;
padding: 5px;
}
.window_caption {
margin: 0px;
font-size: 12px;
font-weight: bold;
text-align: center;
background-color: #E1F6FF;
cursor: pointer;
width: 150px;
text-align: right;
}
</style>
<script language="javascript" type="text/javascript">
<!--//--><![CDATA[//><!--
/***********************************************
* Drag and Drop Script: Dynamic Drive (http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
var dragobject={
z: 0, x: 0, y: 0, offsetx : null, offsety : null, targetobj : null, dragapproved : 0,
initialize:function(){
document.onmousedown=this.drag;
document.onmouseup=function(){this.dragapproved=0}
},
drag:function(e){
var evtobj=window.event? window.event : e;
this.targetobj=window.event? event.srcElement : e.target;
if (this.targetobj.className=="drag"){
this.dragapproved=1;
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0;}
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0;}
this.offsetx=parseInt(this.targetobj.style.left);
this.offsety=parseInt(this.targetobj.style.top);
this.x=evtobj.clientX;
this.y=evtobj.clientY;
if (evtobj.preventDefault)
evtobj.preventDefault();
document.onmousemove=dragobject.moveit;
}
},
moveit:function(e){
var evtobj=window.event? window.event : e;
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px";
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px";
return false;
}
}
}
dragobject.initialize();
//--><!]]>
</script>
</head>
<body>
<div class="drag" id="win">
<div ><span class="window_caption" onclick="document.getElementById('win').style.display='none'">关闭</span></div>
韭菜先生说:<br />
你好<br /><br />
2007-01-01 127.0.0.3
</div>
</body>
</html>