Ответ 1
var fixHelper = function(e, ui) {
ui.children().each(function() {
console.log(e);
$(this).width($(this).width());
});
return ui;
};
$("#sortable1 tbody").sortable({
helper: fixHelper
}).disableSelection();
Не удалось найти простое решение для сортировки jquery для сохранения ширины таблицы во время перетаскивания элемента, forcePlaceholderSize на самом деле не работает на этот раз, если в таблице есть какой-то большой элемент - если я начну перетаскивать его, тогда таблица будет изменена до неподвижного максимальная ширина элемента, поэтому вот что я сделал:
jQuery("#sortable1").sortable({
items: "tbody:not([not-sortable])",
cursor: "move",
zIndex: 9999,
start: function (event, ui) {
var colW = jQuery(".faq_glyph_owner").width();
self.textWidth = ui.item.innerWidth() - colW * 3;
jQuery(".faq_text").width(self.textWidth);
jQuery("#sortable1").css("table-layout", "fixed");
ui.item.find("div").parent().width(self.textWidth + colW);
},
stop: function (event, ui) {
jQuery("#sortable1").css("table-layout", "auto");
}
});
Итак, я обычно просто подсчитываю размер, как и предполагалось, и применяю фиксированный макет к таблице, вот пример этого с таблицей. Поэтому мой вопрос: Есть ли встроенные способы сохранить ширину таблицы при сортировке, как если бы перетаскиваемый элемент все еще находился внутри таблицы? Обратите внимание, что я не хочу, чтобы таблица была исправлена.
P.S. пожалуйста, игнорируйте "jQuery", у нас все еще есть старый прототип кода, который мешает ему
var fixHelper = function(e, ui) {
ui.children().each(function() {
console.log(e);
$(this).width($(this).width());
});
return ui;
};
$("#sortable1 tbody").sortable({
helper: fixHelper
}).disableSelection();
Это код, который я использую для этого. Я создаю вспомогательную функцию, которая получает высоту и ширину всего в строке, а затем явно устанавливает ее в эти высоты и ширину, плюс добавляет строку обратно в качестве заполнителя.
var fixHelper = function (e, ui) {
ui.children().each(function () {
if ($(this).children().length > 0) {
fixHelper(e, $(this));
}
if(parseInt($(this).css("margin-left")) != 0)
$(this).css("margin-left", $(this).css("margin-left"));
if (parseInt($(this).css("margin-right")) != 0)
$(this).css("margin-right", $(this).css("margin-right"));
$(this).width($(this).realWidth(true));
$(this).height($(this).realHeight(true));
});
ui.height(ui.realHeight());
return ui;
};
var unfixHelper = function (ui) {
ui.children().each(function () {
if ($(this).children().length > 0) {
unfixHelper($(this));
}
$(this).css("margin-left", "");
$(this).css("margin-right", "");
$(this).css("width", "");
$(this).css("height", "");
});
ui.css("height", "");
};
var sortableOptions = new Object({
items: "tbody:not([not-sortable])",
cursor: "move",
zIndex: 9999,
helper: fixHelper,
start: function (e, ui) {
ui.placeholder.height(ui.item.height());
ui.placeholder.html("<td colspan=\"10\"> </td>");
},
stop: function (e, ui) {
unfixHelper(ui.item);
ui.placeholder.html("");
}
});
jQuery("#sortable1").sortable(sortableOptions);
Другой файл (real-dimensions.js):
$.fn.realWidth = function (inner) {
var $t = $(this);
var rect = this[0].getBoundingClientRect();
var width;
if (rect.width) {
// `width` is available for IE9+
width = rect.width;
} else {
// Calculate width for IE8 and below
width = rect.right - rect.left;
}
if (inner)
width -= parseInt($t.css("padding-left")) + parseInt($t.css("padding-right"));
return width;
}
$.fn.realHeight = function (inner) {
var $t = $(this);
var rect = this[0].getBoundingClientRect();
var height;
if (rect.height) {
// `height` is available for IE9+
height = rect.height;
} else {
// Calculate height for IE8 and below
height = rect.top - rect.bottom;
}
if (inner)
height -= parseInt($t.css("padding-top")) + parseInt($t.css("padding-bottom"));
return height;
}
В сортируемом виджете есть опция помощник. Его целью является добавление какого-либо поведения в действие отображения перетаскивания. Соответствующая часть модификации:
jQuery('#sortable1').sortable({
helper: fixedWidth
});
function fixedWidth(e, ui) {
var max_w = 0;
// get the max width from all the children
ui.children().each(function() {
var w = $(this).width();
if (w > max_w) max_w = w;
});
// set the width of the table to be the max
$('#sortable1').width(max_w);
return ui;
}
Полную реализацию можно найти в этом JSFiddle. Я получил вдохновение от этого .
Кроме того, если учесть мое мнение, я бы построил эту структуру более простым способом, используя <ul>
вместо <table>
. Как этот. Вам нужно только стиль <ul>
, чтобы иметь фиксированную ширину.
Как насчет этого:
$("#sortable1").sortable({
items: "tbody:not([not-sortable])",
helper: 'clone',
cursor: "move",
zIndex: 9999,
start: function (event, ui) {
$(ui.item[0]).show().css('opacity','0');
},
stop: function (event, ui) {
$(ui.item[0]).css('opacity','1');
}
});
Вы в основном клонируете элемент и вместо того, чтобы скрывать его во время перемещения, вы просто применяете opacity
из 0, а затем применяете opacity
из 1 после его удаления. У меня не было времени проверить это.