html
<div class="dragable"></div>
css
*{
margin: 0;
padding : 0;
}
.dragable {
position: absolute;
width: 100px;
height: 100px;
background: red;
}
js
function Dragdrop(){
var draging=null,
diffX= 0,
diffY=0;
function handleEvent(e){
var e=e || window.event;
var target= e.target|| e.srcElement;
switch (e.type){
case "mousedown":
if(target.className.indexOf('dragable')>-1){
draging=target;
diffX= e.clientX-target.offsetLeft;
diffY= e.clientY-target.offsetTop;
}
break;
case "mousemove":
if(draging){
var left=e.clientX-diffX,
top= e.clientY-diffY;
console.log(e.clientX);
console.log(diffX);
console.log(e.clientX-diffX)
if(left < 0){
left=0;
}
/*下面这段注释掉就没问题*/
if(left > windowRect().winWidth-target.offsetWidth){
left=windowRect().winWidth-target.offsetWidth;
}
/* if(top <= 0){
top=0;
}
if(top>=windowRect().winHeight-target.offsetHeight){
top=windowRect().winHeight-target.offsetHeight;
console.log(top)
}*/
draging.style.left=left+'px';
draging.style.top=top+'px';
}
break;
case "mouseup":
draging=null;
break;
}
}
return {
enable: function () {
document.addEventListener('mousedown',handleEvent,false)
document.addEventListener('mousemove',handleEvent,false)
document.addEventListener('mouseup',handleEvent,false)
},
disable: function () {
document.removeEventListener('mousedown',handleEvent,false);
document.removeEventListener('mousemove',handleEvent,false);
document.removeEventListener('mouseup',handleEvent,false);
}
}
}
function addEvent(){
}
Dragdrop().enable();
function windowRect(){
var winWidth= 0,
winHeight=0;
/* if(window.innerHeight){
winWidth=window.innerWidth;
winHeight=window.innerHeight;
}*/
if(document.compatMode=='CSS1Compat'){
winWidth=document.documentElement.clientWidth;
winHeight=document.documentElement.clientHeight;
}else{
winWidth=document.body.clientWidth;
winHeight=document.body.clientHeight;
}
return {
winWidth:winWidth,
winHeight:winHeight
}
}
写了一段很简单的拖拽,为什么在mousemove里面那段代码注释点就没问题,不注释稍微移动快点就有问题呢?
在拖拽中间,target对象发生了变化造成的。
判断排除就好了。