首页 > 代码库 > js 利用jquery.gridly.js实现拖拽并且排序

js 利用jquery.gridly.js实现拖拽并且排序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src=http://www.mamicode.com/‘javascripts/jquery.js‘ type=‘text/javascript‘></script>"text/css">
  #gridly
  {
    position: relative;
    width: 300px;
  }
  #gridly div{
    background: red;
    width: 60px;
    height: 60px;
  }
</style>
<body>
    <div id="gridly">
      <div user_id="1">1</div>
      <div user_id="2">2</div>
      <div user_id="3">3</div>
      <div user_id="4">4</div>
      <div user_id="5">5</div>
      <div user_id="6">6</div>
      <div user_id="7">7</div>
      <div user_id="8">8</div>
      <div user_id="9">9</div>
      <div user_id="10">10</div>
    </div>

    <script>
        //拖拽组件设置
        var gridly_set = {
        //reordering拖拽前回调函数,reordered拖拽后回调函数
        callbacks:{ reordering: reordering , reordered: reordered },
        //间距
        gutter:60,
        //显示列数
        columns:6
        };

        //加载拖拽组件
        $(‘#gridly‘).gridly(gridly_set);

        //拖拽前回调
        function reordering(){
        console.log(‘reordering‘);
        }

        //拖拽后回调
        function reordered(){
        console.log(‘reordered‘);
        //隔100ms 防止在拖拽放下那一瞬间 返回的left top不准确
        setTimeout(get_user_id_data,100);
        }

        //获取user_ids 并排序 且 ajax提交 
        function get_user_id_data(){
        var dom = $(‘#gridly div‘);
        var tmp = {};
        // 列数的权重 必须保证此数字大于每行的最大宽度 
        // 其实可以用columns*(gutter+base_width) 来计算 但鉴于columns不经常变 没必要这样写
        var col_base_num = 10000;
        dom.each(function(){
          var self = $(this);
          var left_num = self.css(‘left‘).replace(/px/,‘‘);
          var top_num = self.css(‘top‘).replace(/px/,‘‘); 
          //加1 保证top大于0
          var top_tmp = parseInt(top_num) + 1;
          //权重 = left + (top+1)*col_base_num
          var weight = parseInt(left_num) + (top_tmp*col_base_num);
          var user_id = self.attr(‘user_id‘);
          tmp[weight] = user_id;
        });

        //利用对象本身对key的排序功能 实现排序
        var i;
        var arr = [];
        for(i in tmp){
          var r = tmp[i];
          arr.push(r);
        }

        //排序后的数组
        console.log(arr);
        }
    </script>
</body>
</html>

 

jquery 以及 jquery.gridly.js 放至相对目录

 

效果:

技术分享

 

js 利用jquery.gridly.js实现拖拽并且排序