首页 > 语言 > JavaScript > 正文

Javascript实现的类似Google的Div拖动效果代码

2024-05-06 14:23:55
字体:
来源:转载
供稿:网友
代码如下:
JScript 文件:
//检测浏览器 MSIE Firefox
var ie=false,moz=false;
(function()
{//check the browser
var userAgent=navigator.userAgent;
if(userAgent.indexOf("MSIE")!=-1)
ie=true;
else if(userAgent.indexOf("Firefox")!=-1)
moz=true;
})();
//通过ID获得对象
function $E_ID(idString)
{
return document.getElementById(idString);
}
//通过Name获得对象
function $Es_Tag(tagName)
{
return document.getElementsByTagName(tagName);
}
//获得对象绝对位置 obj.offsetparent
function $GetInfo(o)
{
var to=new Object();
to.left=to.right=to.top=to.bottom=0;
var twidth=o.offsetWidth;
var theight=o.offsetHeight;
while(o)
{
to.left+=o.offsetLeft;
to.top+=o.offsetTop;
o=o.offsetParent;
}
to.right=to.left+twidth;
to.bottom=to.top+theight;
return to;
}
//鼠标点击对象确发事件
function $hitTest(obj,event)
{
obj=$GetInfo(obj);
var x=event.clientX;
var y=event.clientY;
if((x>=obj.left&&x<=obj.right)&&(y>=obj.top&&y<=obj.bottom))
 return true;
else
 return false;
}
function Drag(event)
{
this.dragged=false;
this.ao=null;
this.tdiv=null;
this.fixLeft=0;
this.fixTop=0;
this.lastX=event.clientX;
this.lastY=event.clientY;
Drag.mm=null;
this.dragStart=function(event)
{
this.ao=ie?event.srcElement:(moz?event.target:null);
if(ie)
document.body.onselectstart=function()
{
  return false
  }
if(moz&&this.ao.nodeType==3)
 this.ao=this.ao.parentNode;
if(this.ao.tagName=="TD"||this.ao.tagName=="TR")
 this.ao=this.ao.offsetParent.parentNode;
else
 return;
if(this.ao.className!="dragdiv")
 return;
this.tdiv=$E_ID("tmpdiv");
this.tdiv.style.visibility="visible";
this.tdiv.style.filter="alpha(opacity=70)";
if(ie)
 this.tdiv.filters.alpha.opacity=70;
this.tdiv.style.opacity=0.7;
this.tdiv.style.zIndex=100;
this.tdiv.innerHTML=this.ao.innerHTML;
this.tdiv.style.width=this.ao.offsetWidth+"px";
this.tdiv.style.height=this.ao.offsetHeight+"px";
this.tdiv.style.top=$GetInfo(this.ao).top+"px";
this.tdiv.style.left=$GetInfo(this.ao).left+"px";
this.fixTop=parseInt($GetInfo(this.tdiv).top);
this.fixLeft=parseInt($GetInfo(this.tdiv).left);
this.dragged=true;
}
this.onDrag=function(event)
{
if((!this.dragged)||this.ao==null)return;
var tX=event.clientX;
var tY=event.clientY;
this.tdiv.style.left=parseInt(this.fixLeft+tX-this.lastX-document.body.scrollLeft)+"px";
this.tdiv.style.top=parseInt(this.fixTop+tY-this.lastY-document.body.scrollTop)+"px";
for(var m=0;m<$E_ID("root").rows.length;m++)
{
var rootCells=$E_ID("root").rows[m].cells;
for(var i=0;i<rootCells.length;i++)
{
if($hitTest(rootCells[i],event))
{
if(rootCells[i].hasChildNodes())
{
for(var j=0;j<rootCells[i].childNodes.length;j++)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选