javascript 复合数据的定义和使用 ( 小例子 )

思路:主要是先要获取到三个 box 元素的 top 值 和 left 值,然后有复合数据进行存值,再进行数组值的位置移动来实现切换 box 位置效果;

 

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title></title>

</head>

 

<style>

#warp{margin:50px;position:relative;}

#wrap div{position:absolute;width:100px;height:100px;}

.box1{background:orange;left:0px;top:100px;}

.box2{background:red;left:200px;top:50px;}

.box3{background:pink;left:400px;top:100px;}

</style>

 

<body>

 

<input type="button" value="←" id="leftBtn">

<input type="button" value="→" id="rightBtn">

<div id="wrap">

 

  <div class="box1"></div>

  <div class="box2"></div>

  <div class="box3"></div>

</div>

 

</body>

</html>

 

<script>

 

window.onload = function(){

 

 var oLeftBtn = document.getElementById('leftBtn');

 var oRightBtn = document.getElementById('rightBtn');

 var oWrap = document.getElementById('wrap');

 var aBox = oWrap.getElementsByTagName('div');

 //定义一个空数组,来存复合数据

 var arr = [];

 

//定义函数来获取样式表里的值

function getStyle(obj,attr){

   return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,null)[attr];

}



//获取 box 元素的top left值 

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

     //利用复合数据来存两个值,而且把两个值放在一个组,这样就划分为三组数据

    arr.push( [ getStyle(aBox[i],'top') , getStyle(aBox[i],'left') ] );

 }

 

 //向左移动

 oLeftBtn.onclick = function(){

  //往后堆数组中的第一对值

     arr.push(arr[0]);

     //移除数组的第一对值,那么这样的操作就会实现切换效果

     arr.shift();

     //调用设置元素位置的函数

     setAttr();

 }

 

 oRightBtn.onclick = function(){

     //向前堆数组中的第一对值

     arr.unshift(arr[arr.length-1]);

     //移除数组最后一对值,那么也就实现了切换效果

     arr.pop();

     //调用设置元素位置的函数

     setAttr();

 } 

 

//定义每个box的 top 和left 值;

function setAttr(){

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

       //分解一下这个 arr[i][0] ,如果 i=0 时 , arr[0][0] 那么返回值是 arr里面的第一组的第一个值即是top

       aBox[i].style.top = arr[i][0];

       //第二个值就是left值

       aBox[i].style.left = arr[i][1];

    }

  }

}

 

</script>

posted @ 2014-08-04 09:18  Zion0707  阅读(172)  评论(0编辑  收藏  举报