我创建了 Demo通过在我有五个网格的地方使用 packery 和 draggabilly。我可以使用 draggable 对它们进行排序。在我进行排序之后。我需要保存排序后的网格。这里,当我在 dev 中检查时,网格没有移动,只有位置没有改变网格完全正确。
因为我已经通过了id,但是没有用。由于上面提到的问题。
有什么方法可以保存排序顺序吗?我不想使用 localStorage
我的代码如下
HTML
<h1>Image sort</h1>
<div class="packery">
<div class="item w2 h2 i1" tabindex="0">A</div>
<div class="item w2 h2 i2" tabindex="1">B</div>
<div class="item w2 h2 i3" tabindex="2">C</div>
<div class="item w2 h2 i4" tabindex="3">D</div>
<div class="item w2 h2 i5" tabindex="4">E</div>
</div>
JS
// http://packery.metafizzy.co/packery.pkgd.js and
// http://draggabilly.desandro.com/draggabilly.pkgd.js added as external resource
// ----- text helper ----- //
$(function() {
var $container = $('.packery').packery({
columnWidth: 100,
rowHeight: 180,
// disable initial layout
isInitLayout: false
});
var pckry = $container.data('packery');
// ----- packery setup ----- //
// trigger initial layout
$container.packery();
var itemElems = $container.packery('getItemElements');
// for each item element
$( itemElems ).each( function( i, itemElem ) {
// make element draggable with Draggabilly
var draggie = new Draggabilly( itemElem );
// bind Draggabilly events to Packery
$container.packery( 'bindDraggabillyEvents', draggie );
});
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);
max-width: 460px;
}
/* clearfix */
.packery:after {
content: ' ';
display: block;
clear: both;
}
.item {
width: 240px;
height: 140px;
float: left;
background: #C09;
border: 4px solid #333;
border-color: hsla(0, 0%, 0%, 0.3);
font-size: 20px;
color: white;
padding: 10px;
}
.item:hover {
border-color: white;
cursor: move;
}
.item.w2 { width: 400px; }
.item.h2 { height: 140px; }
.item.w2.i1 { background: #ffff00; }
.item.w2.i2 { background: #ff6633; }
.item.w2.i3 { background: #00c6d7; }
.item.w2.i4 { background: #990099; }
.item.w2.i5 { background: #EEEEEE; }
.item.is-dragging,
.item.is-positioning-post-drag {
border-color: white;
background: #09F;
z-index: 2;
}
最佳答案
好吧,“保存” 可能意味着两件事。
- 临时保存值,如您在问题中提到的
localStorage
/Cookies
。问题是,它将解决您在客户端保存订单的问题,即使用户刷新页面并返回,他/她也可以检查这些值并相应地重新排序。缺点是,如果用户删除他/她的缓存和历史记录,当他/她重新访问该页面时,数据可能不存在。 - 另一种选择是使用传统方法,即使用 Ajax 调用并将数据发送到后端脚本(PHP 或 Nodejs),该脚本会将值保存到数据库中。这样,如果存在某种登录系统,您只需将值发布到数据库并以这种方式继续。
这是一个简单的代码,可以给你一个想法(使用 PHP):
JS
$.ajax({
url: 'test.php',
type: 'POST',
data: {order : sortOrder},
success: function(result){
// do something
}
});
测试.php
$order = $_REQUEST['order'];
echo $order;
// Do something here that will store the values to the database
对于 Nodejs,你可以做类似的事情:How to send array of ids correctly in express
希望对你有帮助
关于javascript - 如何保存排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35194599/