Javascript Таблицы данных: убрать нежелательную горизонтальную прокрутку - PullRequest
0 голосов
/ 05 мая 2020

Я использую DataTables для отображения моих данных. Я указываю его ширину 4 bootstrap столбцов. Моя таблица теперь имеет эту нежелательную горизонтальную прокрутку внизу, хотя все данные могут уместиться в указанной ширине:

enter image description here

Прокручивая вправо, я вижу, что поле поиска вверху является причиной этой прокрутки:

enter image description here

Почему поле l ie находится слишком далеко вправо? Как это исправить?

$(document).ready(function () {
	 var data = [
        { title: "The Godfather"},
        { title: "The Shawshank Redemption"},
        { title: "The Lord of the Rings: The Return of the King"},
        { title: "The Godfather: Part II"},
        { title: "Shichinin no samurai"},
        { title: "Buono, il brutto, il cattivo, Il"},
        { title: "Casablanca"},
        { title: "The Lord of the Rings: The Fellowship of the Ring"},
        { title: "The Lord of the Rings: The Two Towers"},
        { title: "Pulp Fiction"}
    ];
    

  var table = d3.select("#myTable");
  var rows = table
            .select('tbody')
            .selectAll('tr')
            .data(data)
            .enter()
            .append('tr');

  var cells = rows
            .selectAll('td')
            .data(function (data_row) {
              return [data_row['title']];
            })
            .enter()
            .append('td')
            .text(function (d) {
              return d;
            });

  $('#myTable').DataTable({
    scrollY: '60vh',
    paging :  false,
  });
});
body {
	padding-top: 1%;
	padding-bottom: 1%;
	background: #585858 !important;
	color: white;
}
<!DOCTYPE html>

<head>
    <title>Data Tabke</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- font awesome lib -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css">
    <!-- bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <!-- dataTable -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">

    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>

    <div class="container">
        <div class="row">
            <div id="FilterableTable" class="col-4">
                <div class="table-responsive">
                    <table class="table table-striped table-dark table-hover table-fit" id="myTable">
                        <thead class='thead-dark'>
                            <tr>
                                <th>My data</th>
       
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
            <div id="FilterableTable2" class="col-8">
                <div class="table-responsive">
                    <table class="table table-striped table-dark table-hover table-fit" id="otherTable">
                        <thead class='thead-dark'>
                            <tr>
                                <th>Col 1</th>
                                <th>Col 2</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
       
        </div>
    </div>


    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"
        integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" 
        crossorigin="anonymous"></script>
    <!-- Popper.js -->
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <!-- dataTable -->
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" charset="utf8"
        src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
    <!-- D3 -->
    <script src="https://d3js.org/d3.v3.min.js"></script>

</body>

ОБНОВЛЕНИЕ с помощью сниппета.

Ответы [ 2 ]

1 голос
/ 05 мая 2020

Я нашел способ решить эту проблему, используя позиционирование DOM самих DataTables. Мне нужно указать структуру таблицы как <f>ti при инициализации таблицы:

$('#myTable').DataTable({
    scrollY: '60vh',
    paging :  false,
    dom    : "<f>ti"
});

, а затем настроить поле поиска так, чтобы оно оставалось плавающим, как:

#myTable_filter {
    float: left !important;
}

id myTable_filter автоматически генерируется DataTables, поэтому мне нужно проверить правильный идентификатор элемента в Chrome.

Объяснение бита <f>ti:

  • Сначала оберните поле поиска (элемент f или Filtering, согласно документации DataTables) в div с < и >.
  • Поместите его перед таблицей или t элемент.
  • Информационный элемент (i) идет последним. Это информационная строка с надписью «Отображение от 1 до x записей x»
0 голосов
/ 05 мая 2020

$(document).ready(function() {
  var data = [{
      title: "The Godfather"
    },
    {
      title: "The Shawshank Redemption"
    },
    {
      title: "The Lord of the Rings: The Return of the King"
    },
    {
      title: "The Godfather: Part II"
    },
    {
      title: "Shichinin no samurai"
    },
    {
      title: "Buono, il brutto, il cattivo, Il"
    },
    {
      title: "Casablanca"
    },
    {
      title: "The Lord of the Rings: The Fellowship of the Ring"
    },
    {
      title: "The Lord of the Rings: The Two Towers"
    },
    {
      title: "Pulp Fiction"
    }
  ];


  var table = d3.select("#myTable");
  var rows = table
    .select('tbody')
    .selectAll('tr')
    .data(data)
    .enter()
    .append('tr');

  var cells = rows
    .selectAll('td')
    .data(function(data_row) {
      return [data_row['title']];
    })
    .enter()
    .append('td')
    .text(function(d) {
      return d;
    });

  $('#myTable').DataTable({
    scrollY: '60vh',
    paging: false,
  });
});
body {
  padding-top: 1%;
  padding-bottom: 1%;
  background: #585858 !important;
  color: white;
}

#myTable_info {
  white-space: normal;
}

.dataTables_wrapper .row:first-child div:first-child {
  width: 0;
  max-width: 0;
  padding: 0;
}

.dataTables_wrapper .row:first-child div:nth-child(2) {
  min-width: 100%;
  padding:0;
}

div.dataTables_wrapper div.dataTables_filter input {
  width: calc(100% - 58px) !important;
  max-width: 320px;
}

#myTable_filter {
  min-width: 100%;
}

.dataTables_wrapper .row:nth-child(3) div:nth-child(1) {
  min-width: 100%
}
<!DOCTYPE html>

<head>
  <title>Data Tabke</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- font awesome lib -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css">
  <!-- bootstrap -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <!-- dataTable -->
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">

  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>

  <div class="container">
    <div class="row">
      <div id="FilterableTable" class="col-4">
        <div class="table-responsive">
          <table class="table table-striped table-dark table-hover table-fit" id="myTable">
            <thead class='thead-dark'>
              <tr>
                <th>My data</th>

              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
      <div id="FilterableTable2" class="col-8">
        <div class="table-responsive">
          <table class="table table-striped table-dark table-hover table-fit" id="otherTable">
            <thead class='thead-dark'>
              <tr>
                <th>Col 1</th>
                <th>Col 2</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>

    </div>
  </div>


  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
  <!-- Popper.js -->
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <!-- dataTable -->
  <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
  <!-- D3 -->
  <script src="https://d3js.org/d3.v3.min.js"></script>

</body>
...