• 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;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>

  • 相关阅读:
    [程序员代码面试指南]递归和动态规划-换钱的方法数(DP,完全背包)
    [程序员代码面试指南]递归和动态规划-换钱的最少货币数(DP,完全背包)
    [程序员代码面试指南]数组和矩阵-未排序数组中累加和为给定值的最长子数组长度
    浅谈RDD
    Java中的移位操作符
    Boolean类源码分析
    IntegerCache详解
    Java Integer类分析
    ArrayList LinkedList Vector
    java的"=="与"equals"
  • 原文地址:https://www.cnblogs.com/zion0707/p/3889367.html
Copyright © 2020-2023  润新知