在很多时候我们会要用到js 拖动效果哦,下面我们就来一款简单的js 拖动实例代码哦。
function getstyle(o,key){return o.currentstyle? o.currentstyle[key] : document.defaultview.getcomputedstyle(o,null)[key]}//'currentstyle' only for ie5.0+
var drag = function(bar, target){
var params = {
startleft:0,
starttop:0,
_x:0,
_y:0,
isdrag:false
};
if(getstyle(target,'left') != 'auto'){params.startleft = getstyle(target,'left')}
if(getstyle(target,'top') != 'auto'){params.starttop = getstyle(target,'top')}
bar.onmousedown = function(e){
e = e?e:window.event; //'event' ie下局部变量,ff下全局变量
params.isdrag = true;
params._x = e.clientx; params._y = e.clienty;
};
document.onmouseup = function(){
params.isdrag = false;
if(getstyle(target,'left') != 'auto'){params.startleft = getstyle(target,'left')}
if(getstyle(target,'top') != 'auto'){params.starttop = getstyle(target,'top')}
};
document.onmousemove = function(e){
var e = e?e:window.event;
if(params.isdrag){
var curx = e.clientx, cury = e.clienty, desl = curx-params._x+parseint(params.startleft), dest = cury-params._y+parseint(params.starttop);
target.style['left'] = desl>=0?desl + 'px':0;
target.style['top'] = dest>=0?dest + 'px':0;
}
}
};
拖拽其实就涉及的鼠标的三个事件,onmousedown,onmouseup,onmousemove,再结合获取鼠标的位置以及层的left和top即可实现类似的效果。