微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – 确定包含项目的对齐顺序

这是我的代码http://codepen.io/helloworld/pen/JoKmQr

让我们假设我从服务器获取了一组数据.数据有标题和订单号.

我有5个数组项,orderNumber从1到5.

现在我想布局5个div,其中每个div位于包装布局系统中的某个位置.

看这个图像:

颜色并不重要.重要的是div的顺序根据他们的订单号.

orderNumber的流程从上到下,从左到右.

题:

如何确定布局系统中div的顺序?他们自动布局到我想要的流程?或者手动订购的提示也没关系:-)

HTML

<h1>Packery demo - Draggabilly</h1>
<div class="packery js-packery" data-packery-options='{ "isHorizontal": true }'>
  <div class="item w1"></div>
  <div class="item h4"></div>
  <div class="item w2"></div>
  <div class="item w3"></div>
  <div class="item h2"></div>
</div>

CSS

* {
  -webkit-Box-sizing: border-Box;
     -moz-Box-sizing: border-Box;
          Box-sizing: border-Box;
}

body { font-family: sans-serif; }

.packery {
  background: #FDD;
  background: hsla(45,100%,40%,0.2);
  counter-reset: item;
  height: 400px;
}

/* clearfix */
.packery:after {
  content: ' ';
  display: block;
  clear: both;
}

.item {
  width: 80px;
  height: 80px;
  float: left;
  border: 4px solid #333;
  border-color: hsla(0,0%,0.3);
}

.item:hover {
  border-color: white;
  cursor: move;
}

.item.w1 { width:   80px; background:green; }
.item.w2 { width:   80px; background:blue; }
.item.w3 { width:   80px; background:yellow; }
.item.h2 { height:  80px; background:red; }
.item.h4 { height: 160px; width:80px; background:orange;}

.item:before {
  counter-increment: item;
  content: counter(item);
  display: block;
  color: white;
  padding-top: 0.2em;
  text-align: center;
  font-size: 18px;
}

.item.is-dragging,.item.is-positioning-post-drag {
  border-color: white;
  background: #09F;
  z-index: 2;
}

JS

// external js
// http://packery.Metafizzy.co/packery.pkgd.js
// http://draggabilly.desandro.com/draggabilly.pkgd.js

$( function() {

  var $container = $('.packery').packery({
    columnWidth: 80,rowHeight: 80
  });

  $container.find('.item').each( function( i,itemElem ) {
    // make element draggable with Draggabilly
    var draggie = new Draggabilly( itemElem );
    // bind Draggabilly events to Packery
    $container.packery( 'bindDraggabillyEvents',draggie );
  });

});

解决方法

为了获得packery给出元素的索引,必须调用’getItemElements’来获得每个元素的准确索引.原因是packery实际上并没有重新排序DOM上的项目,它保留了自己的索引.

这是我解决这个问题的方法

var $itemElems = $($container.packery('getItemElements'));

orderItems = function() {
var itemElems = $($container.packery('getItemElements'));
$(itemElems).each(function(i,itemElem) {
$(itemElem).attr('data-module-index',i); 
// adds a data attribute called data-module-index to the element and makes the value its actual index.
                });
            };
orderItems();

因此,当您重新布置项目时,请确保保存/使用与packery为您提供上述功能的元素相同的索引顺序

原文地址:https://www.jb51.cc/jquery/177186.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐