拖拽元素自定义html模板,JS实现的自定义网页拖动类

本文实例讲述了JS实现的自定义网页拖动类。分享给大家供大家参考,具体如下:

先来看运行效果截图如下:

d2960856b15928b2d0e89d568c037056.png

在线演示地址如下:

具体代码如下:

/p>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

自写的拖动类……

var d=document;//给document对象一个通用的事件侦听方法

d.addListener=function(e,f,b){

this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b);

}

d.removeListener=function(e,f,b){

this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b);

}

function $(){//接收一个id参数,返回带有startDrag方法的对象

var o=document.getElementById(arguments[0]);

o.addListener=function(e,f,b){

this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b);

}

o.removeListener=function(e,f,b){

this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b);

}

o.startDrag=function(obj){//参数obj默认为o本身,可以传其它参数以确定要移动的对象

var obj=obj?obj:o;

var sx,sy;

o.style.cursor="move";

o.addListener("mousedown",function(e){

e||event;

if(e.button==1||e.button==0){

sx=e.clientX-obj.offsetLeft;sy=e.clientY-obj.offsetTop;

d.addListener("mousemove",move,false);

d.addListener("mouseup",stopDrag,false);

}

},false);

var stopDrag=function(){

d.removeListener("mousemove",move,false);

d.removeListener("mouseup",stopDrag,false);

}

var move=function(e){

e||event;

window.getSelection ? window.getSelection().removeAllRanges() :

document.selection.empty();

if(e.preventDefault)e.preventDefault();//这两句便是解决firefox拖动问题的.

with (obj.style){

position="absolute"

left=e.clientX-sx+"px";

top=e.clientY-sy+"px";

}

}

}

return o;

}

window.οnlοad=function(){$("ok").startDrag($("os"))}//本例中拖动ok元素,移动其父元素

*{margin:0;padding:0}

#ok{width:215px;height:170px;background:url(images/sample1.gif)}

#os{width:400px;height:300px;background:#09f;left:300px}

#os2{width:400px;height:300px;background:#f90;}

希望本文所述对大家JavaScript程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值