leo列

导航

点击上,下,左,右进行轮播的demo

一,HTML代码

<div id="box">
  <div id="slide_box">
    <ul id="slide">
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div id="up_btn"></div>
  <div id="down_btn"></div>
</div>

必须要有的几个id是:"slide_box","slide",如果是左右轮播那么就是左右的id  "left_btn","right_btn"

                                                      如果是上下轮播那么就是上下的id  "up_btn","down_btn"

二,样式

#slide_box{ position:relative; over-flow:hidden;}
#slide{ position:absolute;}

以及一些宽和高是必不可少的。

 

三,javascript代码

//移动代码
function
moveElement(elem,final_x,final_y,delay){ var xpos = getCssStyle(elem,"left"); var ypos = getCssStyle(elem,"top"); if(elem.moveMent){ clearTimeout(elem.moveMent); } if(xpos==final_x&&ypos==final_y) { return true; } if(xpos<final_x) { var dist = Math.ceil((final_x-xpos)/10); xpos+=dist; } if(xpos>final_x) { var dist = Math.ceil((xpos-final_x)/10); xpos-=dist; } if(ypos<final_y) { var dist = Math.ceil((final_y-ypos)/10); ypos+=dist; } if(ypos>final_y) { var dist = Math.ceil((ypos-final_y)/10); ypos-=dist; } elem.style.left=xpos+"px"; elem.style.top=ypos+"px"; elem.moveMent = setTimeout(function(){moveElement(elem,final_x,final_y,delay);},delay); }
//计算样式
function getCssStyle(elem,pro){ var getComputed=""; if(elem.currentStyle) { getComputed=elem.currentStyle[pro]; }else if(document.defaultView.getComputedStyle){ getComputed=document.defaultView.getComputedStyle(elem,null)[pro]; } return parseInt(getComputed); }
//加载执行 window.onload
=function(){ if(!document.getElementById("slide")) return false; if(!document.getElementById("slide_box")) return false; var slide = document.getElementById("slide"); var slide_box = document.getElementById("slide_box"); var count=0;
//左右轮播
if(document.getElementById("left_btn")&&document.getElementById("right_btn")) { var left_btn = document.getElementById("left_btn"); var right_btn = document.getElementById("right_btn"); var w = getCssStyle(slide,"width"); var small_w = getCssStyle(slide_box,"width"); var n = Math.floor(w/getCssStyle(slide_box,"width")); left_btn.onclick=function(){ if(count>0) { count--; final_x=-count*small_w; moveElement(slide,final_x,0,10); } } right_btn.onclick=function(){ if(count<n) { count++; final_x=-count*small_w; moveElement(slide,final_x,0,10); } } }else if(document.getElementById("up_btn")&&document.getElementById("down_btn")) //上下轮播 { var up_btn = document.getElementById("up_btn"); var down_btn = document.getElementById("down_btn"); var h = getCssStyle(slide,"height"); var small_h = getCssStyle(slide_box,"height"); var n = Math.floor(h/getCssStyle(slide_box,"height")); up_btn.onclick=function(){ if(count>0) { count--; final_y=-count*small_h; moveElement(slide,0,final_y,10); } } down_btn.onclick=function(){ if(count<n) { count++; //alert(count); final_y=-count*small_h; moveElement(slide,0,final_y,10); } } } }

posted on 2012-09-18 18:27  leo列  阅读(361)  评论(0编辑  收藏  举报