js如何实现惯性滑动效果

JavaScript08

js如何实现惯性滑动效果,第1张

主要思路是:鼠标当前点到下一点直接间隔计算出速度。这样就实现了惯性滑动效果。

下面是简单的js代码实现:仅供参考:

<style>    

#div1{ width:100px height:100px background:red position:absolute left:0px top:0}    

</style>    

<script>    

window.onload=function(){    

var oDiv=document.getElementById('div1')    

var iSpeedX=0    

var iSpeedY=0     

var lastX=0    

var lastY=0    

var timer=null     

oDiv.onmousedown=function(ev){    //div的鼠标按下事件,主要计算鼠标当前位置,和移动位置。这样可以计算出鼠标移动速度。

var oEvent=ev || event    

var disX=oEvent.clientX-oDiv.offsetLeft    

var disY=oEvent.clientY-oDiv.offsetTop      

clearInterval(timer)      

document.onmousemove=function(ev){   //鼠标拖动事件。 

var oEvent=ev || event     

oDiv.style.left=oEvent.clientX-disX+'px'    

oDiv.style.top=oEvent.clientY-disY+'px'    

iSpeedX=oEvent.clientX-lastX    

iSpeedY=oEvent.clientY-lastY     

lastX=oEvent.clientX    

lastY=oEvent.clientY

}    

document.onmouseup=function(){    //当鼠标抬起后,清掉移动事件。

document.onmousemove=null    

document.onmouseup=null

oDiv.releaseCapture && oDiv.releaseCapture()      

startMove()    

}    

oDiv.setCapture && oDiv.setCapture()    

return false

}         

function startMove(){    //移动函数,主要操作是计算鼠标移动速度和移动方向。

clearInterval(timer)    

timer=setInterval(function(){    

iSpeedY+=3    

var t=oDiv.offsetTop+iSpeedY    

var l=oDiv.offsetLeft+iSpeedX    

if(t>document.documentElement.clientHeight-oDiv.offsetHeight){    

t=document.documentElement.clientHeight-oDiv.offsetHeight    

iSpeedY*=-0.8    

iSpeedX*=0.8

}     

if(t<0){    

t=0    

iSpeedY*=-0.8    

iSpeedX*=0.8

}    

if(l>document.documentElement.clientWidth-oDiv.offsetWidth){    

l=document.documentElement.clientWidth-oDiv.offsetWidth

    

iSpeedX*=-0.8    

iSpeedY*=0.8    

}    

if(l<0){    

l=0    

iSpeedX*=-0.8    

iSpeedY*=0.8

    

}    

    

oDiv.style.left=l+'px'    

oDiv.style.top=t+'px'    

    

if(Math.abs(iSpeedX)<1)iSpeedX=0    

if(Math.abs(iSpeedY)<1)iSpeedY=0    

if(iSpeedX==0 && iSpeedY==0 && t==document.documentElement.clientHeight-oDiv.offsetHeight){    

clearInterval(timer)    

}    

document.title=i++    

},30)

}    

}    

</script>    

</head>    

<body>    

<div id="div1"></div>    

</body>

绑定触摸事件 touchstart touchmove

监听触摸事件event.touches中触摸点的数量

在touchmove事件做判定,如果 event.touches.length==2 则记录此次两点之间的距离:Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2))

在手指移动过程中针对每一次的两点距离进行比较。如果相对上次较大则放大,否则缩小。div的缩放通过transform:scale(x)进行控制

写代码有些麻烦,给个关键建议。你大概是在拖动页面上遇到麻烦吧!要实现在触控设备上手指拖动元素,不能用mousemove哟,这个是没用的,要用到touchstart(手指接触触摸屏),touchmove(手指在触摸屏上移动),touchend(手指离开触摸屏)。touchmove调用的函数里最好填上event.preventDefault() 否则有些浏览器对touchmove也不管用哟!这个还可以开发多点触控,你自己去研究吧!

有关触摸事件参考这里: http://zm10.sm.cn/?src=http%3A%2F%2Fwww.2cto.com%2Fkf%2F201401%2F272575.html&uid=374119f2442b2126e94b23ef1419d180&hid=6b989aa1182219e3e0883131a232b00a&pos=2&cid=9&pi=&di=&time=1412014181458&from=click&restype=1&pagetype=0000000000000402