<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS惯性拖拽</title>
<style>
*{ margin:0; padding:0; list-style:none; font-family: "微软雅黑","张海山锐线体简"}
#div1{width:200px;height:200px;position:absolute;left:0;top:0;}
.box{width:10px;height:10px;background:green; position:absolute;left:0;top:0;}
</style>
<script>
window.onload=function(){
var oDiv=document.getElementById('div1');
oDiv.onmousedown=function(ev){
var speedX=0,speedY=0; //要求的速度
var lastX=0,lastY=0; //最后一次的距离
var oEvt=ev||event;
var disX=oEvt.clientX-oDiv.offsetLeft;
var disY=oEvt.clientY-oDiv.offsetTop;
document.onmousemove=function(ev){
var oEvt=ev||event;
oDiv.style.left=oEvt.clientX-disX+'px';
oDiv.style.top=oEvt.clientY-disY+'px';
speedX = oDiv.offsetLeft-lastX
speedY = oDiv.offsetTop-lastY
lastX=oDiv.offsetLeft
lastY=oDiv.offsetTop
console.log(lastX,speedX);
};
document.onmouseup=function(){
document.onmousemove=document.onmouseup=null;
//alert(speedX+'|'+speedY);
move(oDiv,speedX,speedY);
};
return false;
};
function move(obj,speedX,speedY){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
speedX*=0.95 //摩擦
speedY*=0.95 //摩擦
obj.style.left=obj.offsetLeft+speedX+'px';
obj.style.top=obj.offsetTop+speedY+'px';
if(Math.abs(speedX)<1) speedX=0;
if(Math.abs(speedY)<1) speedY=0;
if(speedX==0&&speedY==0){
clearInterval(obj.timer);
}
console.log(speedX,speedY);
},30);
}
};
</script>
</head>
<body>
<div id="div1"><img style="width:100%" src="cc.png" alt=""></div>
</body>
</html>
效果如下: