当前位置:首页 »“秋了秋”个人博客 » 前端编程 » JavaScript完美弹性运动+拖拽

JavaScript完美弹性运动+拖拽

作者:秋了秋 发表时间:2016年01月28日

代码详情:

请拖动我

<style>
#div1{background:green;width:100px;height:100px;border-radius:50%;background-size: cover;position:absolute;cursor:default;top:100px;left:100px;color:white;line-height:100px;text-align:center;}
</style>
<div id="div1">请拖动我</div>
<script>
window.onload=function(){
var oDiv=document.getElementById('div1'),width=oDiv.offsetWidth,height=oDiv.offsetWidth;
var speedX=0,speedY=0,lastX=0,lastY=0;
var scwidth=document.documentElement.clientWidth||document.body.clientWidth;
var scheight=document.documentElement.clientHeight||document.body.clientHeight;
var timer=null;

oDiv.onmousedown=function(ev){//拖拽功能
clearInterval(timer);
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';
/**判断边界处理**/
if((oEvt.clientX+width-disX)>=scwidth){
oDiv.style.left=scwidth-width+'px';
}
else if((oEvt.clientX-disX)<=0){
oDiv.style.left=0;
}
if((oEvt.clientY+height-disY)>=scheight){
oDiv.style.top=scheight-height+'px';
}
else if((oEvt.clientY-disY)<=0){
oDiv.style.top=0;
}

speedX=oDiv.offsetLeft-lastX;//移动一瞬间的差异,用于定义速度,差异越大,速度越大,同下
speedY=oDiv.offsetTop-lastY;

lastX=oDiv.offsetLeft;//获取此时此刻目标的位置
lastY=oDiv.offsetTop;

};
document.onmouseup=function(){//注意了,松手了~
document.onmouseup=document.onmousemove=null;//注销抬起左键和按住鼠标左键&移动事件
oDiv.releaseCapture && oDiv.releaseCapture();//释放鼠标监控
move('div1');//执行运动函数
};
oDiv.setCapture && oDiv.setCapture();//监控整个window系统的鼠标事件,并全部指向这个oDiv
return false;//解除默认行为,如按住鼠标移动时选中文字等
};

function move(tarGet){//运动函数
clearInterval(timer);
var oDiv=document.getElementById(tarGet);
var fnMove=function(){
speedY+=3;//松手之后以3的加速继续运行
var t=oDiv.offsetTop+speedY;
var l=oDiv.offsetLeft+speedX;
/**判断边界**/
if(t>=scheight-oDiv.offsetHeight){
speedY*=-0.95;//设置弹性系数,同下
speedX*=0.95;
t=scheight-oDiv.offsetHeight;
}else if(t<=0){
speedY*=-0.95;
speedX*=0.95;
t=0;
}

if(l>=scwidth-oDiv.offsetWidth){
speedX*=-0.95;
speedY*=0.95;
l=scwidth-oDiv.offsetWidth;
}else if(l<=0){
speedX*=-0.95;
speedY*=0.95;
l=0;
}

oDiv.style.top=t+'px';//定位目标
oDiv.style.left=l+'px';

if(Math.abs(speedX)<1) speedX=0;//在值够小的情况下强制让它变成0,同下
if(Math.abs(speedY)<1) speedY=0;

if(speedX==0 && speedY==0 && t==scheight-oDiv.offsetHeight){
clearInterval(timer);//清除定时器
}
}
timer=setInterval(fnMove, 30);
}
};
</script>
0
文章作者: “秋了秋”个人博客,本站鼓励原创。
转载请注明本文地址:http://netblog.cn/blog/430.html
目录: 前端编程标签: 弹性运动 6862次阅读

请求播放音乐,请点击播放

登 录
点击获取验证码
还没账号?点击这里