首页 > 代码库 > Javascript:实操---类似京东图片点击切换

Javascript:实操---类似京东图片点击切换

CSS部分

<style>
*{ margin:0; padding:0;}
#div1{ width:670px; height:150px; margin:20px auto; position:relative; overflow:hidden;}
.out{ width:5000px; height:150px; overflow:hidden; position:absolute;}
.out ul{ height:150px; list-style:none; position:absolute; left:0;}
.out li,.out img{ float:left;}
.left{ position:absolute; height:150px; width:20px; background:white url(images/6.jpg) center center no-repeat; opacity:0.7; left:0; top:0;}
.right{ position:absolute; height:150px; width:20px; background:white url(images/7.jpg) center center no-repeat; opacity:0.7; right:0; top:0;}
</style>

HTML部分

<div id="div1">
    <div class="out">
    <ul>
        <li><img src="http://www.mamicode.com/images/1.jpg" /></li>
        <li><img src="http://www.mamicode.com/images/2.jpg" /></li>
        <li><img src="http://www.mamicode.com/images/3.jpg" /></li>
        <li><img src="http://www.mamicode.com/images/4.jpg" /></li>
        <li><img src="http://www.mamicode.com/images/5.jpg" /></li>
    </ul>
    </div>
    <div class="left"></div>
    <div class="right"></div>
</div>JS部分

<script src="http://www.mamicode.com/tween.js"></script>

<script>

function byClass(el,oClass){

  var aElement=el.getElementsByTagName("*");

  var arr=[];

  for(var i=0;i<aElement.length.i++){

    if(aElement[i].className==oClass){

      arr.push(aElement[i]);

    }

  }

  return arr;

}

window.onload=function(){

  var oOut=byClass(document,"out")[0];

  var oLeft=byClass(document,"left")[0];

  var oRight=byClass(document,"right")[0];

  var aLi=oOut.getElementsByTagName("li");

 

  var index=0;

  var timer=null

  var t=30;

  var endT=30;

 

  function move(){

    var start=oOut.offsetLeft;

    var end=-index*aLi[0].offsetWidth;

    var change=end-start;

    t=0;

    clearInterval(timer);

    timer=setInterval(function(){

      t++;

      if(t==endT){

        clearInterval(timer);

      }

      oOut.style.left=Tween.Expo.easeOut(t,start,change,endT)+"px";

    },30);

  }

  oLeft.onclick=function(){

    if(oOut.offsetLeft%aLI[0].offsetWidth==0){

      index--;

      if(index<0){

        index=aLi.length-1;

      }

      move();

    }

  }

  oRight.onclick=function(){

    if(oOut.offsetLeft%aLi[0].offsetWidth==0){

      index++;

      if(index>=aLi.length-1){

        index=0;

      }

      move();

    }

  }

}

</script>