实现步骤:
1、实现可拖动;
2、判断拖动的方向;
3、实现弹性运动;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
}
body{
background: #000000;
}
#wrap{
width: 320px;
height: 480px;
overflow:hidden;
position: absolute;
top: 50%;
left: 50%;
margin-left: -160px;
margin-top: -240px;
background: url(img/red.png) no-repeat 137px 217px;
}
#ul1{
width: 1280px;
height: 480px;
position: absolute;
cursor: pointer;
}
#ul1 li{
width: 320px;
height: 480px;
float: left;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oUl=document.getElementById("ul1");
var aLi=oUl.getElementsByTagName('li');
var iWidth=aLi[0].offsetWidth;
var disX=0;
var downX=0;
var iNow=0;
var timer=null;
var iSpeed=0;
oUl.onmousedown=function(ev){
var ev= ev || window.event;
clearInterval(timer);
downX=ev.clientX;
disX=ev.clientX-oUl.offsetLeft;
document.onmousemove=function(ev){
var ev= ev || window.event;
oUl.style.left=ev.clientX-disX+'px';
}
document.onmouseup=function(ev){
document.onmousemove=null;
document.onmouseup=null;
var ev= ev || window.event;
//通过比较鼠标抬起时和鼠标按下时的位置来判断拖动方向
if (ev.clientX>downX && Math.abs(ev.clientX-downX)>80 ) {
//alert('you');
if (iNow!=0) {
iNow--;
}
startMove(-iNow*iWidth);
}else{
//alert('zuo');
if (iNow!=aLi.length-1) {
iNow++;
}
startMove(-iNow*iWidth);
}
}
return false;
}
function startMove(iTarget){
clearInterval(timer);
timer=setInterval(function(){
iSpeed+=(iTarget-oUl.offsetLeft)/5;
iSpeed*=0.7;
if ( Math.abs(iSpeed)<1 && Math.abs(iTarget-oUl.offsetLeft)<1 ) {
clearInterval(timer);
iSpeed=0;
oUl.style.left=iTarget+'px';
}else{
oUl.style.left=oUl.offsetLeft+iSpeed+'px';
}
},30)
}
}
</script>
</head>
<body>
<div id="wrap">
<ul id="ul1">
<li style="background: url(img/640-960-1.png); background-size: 320px 480px;"></li>
<li style="background: url(img/640-960-2.png); background-size: 320px 480px;"></li>
<li style="background: url(img/640-960-3.png); background-size: 320px 480px;"></li>
<li style="background: url(img/640-960-4.png); background-size: 320px 480px;"></li>
</ul>
</div>
</body>
</html>