日期:2014-05-16  浏览次数:20329 次

js 实现的拖拽功能

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
?<head>
? <title> New Document </title>
? <meta name="Generator" content="EditPlus">
? <meta name="Author" content="">
? <meta name="Keywords" content="">
? <meta name="Description" content="">
? <script type="text/javascript">
function ObjectDragDrop(obj){
??? var me = this;
??? this.foo = (typeof obj=="string")?document.getElementById(obj):obj;
????
??? this.foo.onmousedown = function(e){
????????? var foo = me.foo;
????????? e = e||event;?

foo.style.filter = 'alpha(opacity=70)';
??? foo.style.position = 'absolute';
????????? var fstartX = foo.style.left;
????????? var fstartY = foo.style.top;
????????? var fstartx = 0;
????????? var fstarty = 0;
???????
????????? if(fstartY!=''){
?????????? fstartx = parseInt(fstartX.substr(0,fstartX.length-2));
????????? }else{
????????? ?? fstartx = foo.offsetLeft;
????????? }
????????? if(fstartX!=''){
?????????? fstarty = parseInt(fstartY.substr(0,fstartY.length-2));
????????? }else{
????????? ?? fstarty = foo.offsetTop;
????????? }
????????? if( e.layerX ){ foo.oOffset = {x:e.layerX,? y:e.layerY };??? }
????????? else????????? { foo.oOffset = {x:e.clientX-fstartx, y:e.clientY-fstarty};?? }
????????
????????? document.onmousemove = me.drag;
????????? document.onmouseup?? = me.drop;
????????? document.onselectstart = function(){ return false; };?????????
??? }
????
??? this.drag = function(e){
????????? var foo = me.foo;
????????? e=e||event;
????????? foo.style.top? = e.clientY - foo.oOffset.y + "px";
????????? foo.style.left = e.clientX - foo.oOffset.x + "px";
??? }
????
??? this.drop = function(e){
????????? var foo = me.foo;
????????? e=e||event;
????????? foo.style.filter = 'alpha(opacity=100)';

????????? document.onmousemove = document.onmouseup = document.onselectstart = null;????
??? }????
}
</script>
?</head>

?<body>
? <div id="kkkkk" style="width:300px;height:250px;border-style:solid;border-width:1px;border-color:green;background-color:#C8F1C1;
?background-image:url('http://img.alimama.cn/adbrand/adboard/picture/2011-06-07/123114930001110607104555.jpg')">
???<div style="width:100%;border-style:solid;border-width:1px;border-color:#97C896;cursor:move;">
???<div style="border-style:solid;border-width:1px;border-color:#A6D7A5;cursor:move;">
???<div style="border-style:solid;border-width:1px;border-color:#AEEBAA;cursor:move;">
???<div style="border-style:solid;border-width:1px;border-color:#B6F3B2;cursor:move;">
???<div style="border-style:solid;border-width:1px;border-color:#C6ECBE;cursor:move;">
???</div>
???</div>
???</div>
???</div>
???</div>
? </div>?</body>
?<script type="text/javascript">
var test1 = new? ObjectDragDrop("kkkkk");
?</script>
</html>