Прокрутка таблицы (как карусель)
Доброго времени суток!
Снова прошу помощи. Подскажите, пожалуйста, как можно реализовать прокрутку столбцов таблицы. Пока идей ни каких нету. Но думается это что то похожее на карусель для картинок. Пример можно увидеть на https://auto.ru/ если добавить в сравнение штук 12 машин. В хедере таблицы появляется стрелочка для прокручивания. При ее клике таблица прокручивается. Можно прокрутить обратно. Вероятно это делается для не больших дисплеев или телефонов, что бы можно было смотреть всегда например по 3 столбца, а дальше прокрутка и снова 3 столбца. Прошу подсказать если кто реализовывал, может есть пример, что бы можно было модифицировать под себя. Заранее благодарен. Таблица примерно такая: <table class="table" id="ex3"> <tbody> <tr> <th></th> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th class="nosort">header</th> </tr> <tr> <td class="remove_button"></td> <td>1-1</td> <td>1-2</td> <td>1-3</td> <td>1-4</td> </tr> <tr> <td class="remove_button"></td> <td>2-1</td> <td>2-2</td> <td>2-3</td> <td>2-4</td> </tr> <tr> <td class="remove_button"></td> <td>3-1</td> <td>3-2</td> <td>3-3</td> <td>3-4</td> </tr> <tr> <td class="remove_button"></td> <td>4-1</td> <td>4-2</td> <td>4-3</td> <td>4-4</td> </tr> </tbody> </table> |
Попробую. По другому спросить.
Сделал следующее: <div class="scroll-table col-md-offset-2 col-md-2"> <button class="ComparisonHeader__arrowLeft btn btn-danger" id="left-button"> <- </button> <button class="ComparisonHeader__arrowRight btn btn-danger" id="right-button"> -> </button> </div> На кнопки повесил: $("#right-button").click(function() { event.preventDefault(); $(".table-responsive").animate( { scrollLeft: "+=400px" }, /*"slow"*/ ); }); $("#left-button").click(function() { event.preventDefault(); $(".table-responsive").animate( { scrollLeft: "-=400px" }, /*"slow"*/ ); }); Таблицу обернул в: <div class="center table-responsive" style="overflow-x: auto;"> <table class="table" id="ex4"> ... </table> </div> В таком виде прокрутка работает как карусель, но это не совсем то. Возможно ли сделать так - по умолчанию показывается 4 столбца таблицы, если столбцов больше чем 4 то по клике на кнопку <button id="right-button"> -> </button> 1-ый столбец таблицы делается невидимым, а 5-ый столбец добавляется (снова 4-столбца). А по клику на <button id="left-button"> <- </button> 5-ый столбец становится невидимым а 1-ый добавляется (снова видим 4 столбца). Может кто то реализовывал? |
таблица скрытие столбцов
Цитата:
<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(function() { let index = 0, max = 4, length = 5; const hideCells = _ => document.querySelectorAll("#ex3 tr") .forEach(({ cells }) => { [...cells].forEach(({ style }, i) => style.display = i < index || i >= index + max ? "none" : "") }) hideCells(); $(".scroll-table").on("click", "[data-up]", function() { index += +this.dataset.up; index = Math.max(0, Math.min(length - max, index)); hideCells() }) }); </script> </head> <body> <table class="table" id="ex3"> <tbody> <tr> <th>header 0</th> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th class="nosort">header 4</th> </tr> <tr> <td class="remove_button">0</td> <td>1-1</td> <td>1-2</td> <td>1-3</td> <td>1-4</td> </tr> <tr> <td class="remove_button">0</td> <td>2-1</td> <td>2-2</td> <td>2-3</td> <td>2-4</td> </tr> <tr> <td class="remove_button">0</td> <td>3-1</td> <td>3-2</td> <td>3-3</td> <td>3-4</td> </tr> <tr> <td class="remove_button">0</td> <td>4-1</td> <td>4-2</td> <td>4-3</td> <td>4-4</td> </tr> </tbody> </table> <div class="scroll-table col-md-offset-2 col-md-2"> <button class="ComparisonHeader__arrowLeft btn btn-danger" id="left-button" data-up="-1"> <- </button> <button class="ComparisonHeader__arrowRight btn btn-danger" id="right-button" data-up="1"> -> </button> </div> </body> </html> |
Спасибо! Все работает. :dance: :thanks: Еще один вопрос, как то можно зафиксировать самый первый tr? тот где
<td class="remove_button">0</td> Там просто у меня кнопки удаления строки. Хотелось бы что бы они остались. Пробовал const hideCells = _ => document.querySelectorAll("#ex4 tr:not(:first-child)") |
Dolf,
пробуйте $(function() { let index = 1, max = 4, length = 5; const hideCells = _ => document.querySelectorAll("#ex3 tr") .forEach(({ cells }) => { [...cells].forEach(({ style }, i) => i && (style.display = i < index || i >= index + max ? "none" : "") ) }) hideCells(); $(".scroll-table").on("click", "[data-up]", function() { index += +this.dataset.up; index = Math.max(1, Math.min(length - max, index)); hideCells() }) }); |
Ни когда бы не додумался) Я все пытался селекторами исключить. :victory:
|
|
Vlasenko Fedor,
Спасибо за идею! Почитаю. Но там у меня + еще столбцы перемещать местами можно, и удалять и восстанавливать не нужные строки. Если такое возможно в готовой библиотеке, было конечно супер) |
Думаю все там есть
пример перемещения столбцов https://editor.datatables.net/exampl.../exportButtons смотрите документацию и примеры |
Часовой пояс GMT +3, время: 08:07. |