Как открыть UL согласно позиции кнопки строки таблицы в jQuery? - PullRequest
1 голос
/ 09 января 2020

У меня есть таблица, сейчас есть три строки с кнопкой Add Section (она может быть увеличена). Когда я нажимаю Add Section, переключение UL работает нормально только для первого ряда Add Section, когда я нажимаю вторую кнопку, затем UL открывается верхней кнопкой. Как я могу это исправить?

Проще говоря, я хочу открыть UL согласно позиции кнопки. Как я могу сделать это с одним UL списком?

Мой код: -

$(function(){
            $('.add-section').click(function(){
                $('.section-area').toggle();
            });
        })
.section-area{ background:#fff; padding: 5px; border-radius: 4px; box-shadow: 2px 4px 10px rgba(39, 59, 69, 0.4); width: 100px; position: absolute; top:61px; right:140px; display: none;}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>


  <table class="table table-bordered">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>John</td>
            <td>Doe</td>
            <td>john@example.com</td>
            <td><button class="add-section btn btn-primary">Add Section</button></td>
        </tr>
          <tr>
            <td>Mary</td>
            <td>Moe</td>
            <td>mary@example.com</td>
            <td><button class="add-section btn btn-primary">Add Section</button></td>
          </tr>
          <tr>
            <td>July</td>
            <td>Dooley</td>
            <td>july@example.com</td>
            <td><button class="add-section btn btn-primary">Add Section</button></td>
          </tr>
        </tbody>
      </table>

      <div class="section-area">
          <ul>
              <li>Add 1</li>
              <li>Add 2</li>
              <li>Add 3</li>
          </ul>
      </div>

Ответ приветствуется!

Ответы [ 2 ]

4 голосов
/ 09 января 2020

Ваша проблема возникает из-за того, что top и right вашего section-area исправлены. Чтобы это исправить, просто измените его так, чтобы top и right менялись в зависимости от того, какая кнопка нажата. Вот рабочий пример:

$(function(){
    $('.add-section').click(function(){
        let buttonTopPosition = $(this).offset().top
        let buttonLeftPosition = $(this).offset().left
        let sectionAreaWidth = $(this).outerWidth()
        $('.section-area').toggle();
        $('.section-area').css({top: buttonTopPosition, left: buttonLeftPosition - sectionAreaWidth})
    });
})
.section-area{
  background:#fff;
  padding: 5px;
  border-radius: 4px;
  box-shadow: 2px 4px 10px rgba(39, 59, 69, 0.4);
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  display: none;}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>


<table class="table table-bordered">
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Email</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@example.com</td>
      <td><button class="add-section btn btn-primary">Add Section</button></td>
  </tr>
    <tr>
      <td>Mary</td>
      <td>Moe</td>
      <td>mary@example.com</td>
      <td><button class="add-section btn btn-primary">Add Section</button></td>
    </tr>
    <tr>
      <td>July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
      <td><button class="add-section btn btn-primary">Add Section</button></td>
    </tr>
  </tbody>
</table>

<div class="section-area">
    <ul>
        <li>Add 1</li>
        <li>Add 2</li>
        <li>Add 3</li>
    </ul>
</div>

Я изменил ваши CSS top и left на изначально 0. Затем я обновлю эти свойства при нажатии кнопки (обновляется с помощью jQuery).

1 голос
/ 09 января 2020

Я советую вам использовать раскрывающийся список bootstrap по многим причинам:

  1. ваш код плохо обслуживается, например. когда вы щелкаете по второму ряду, если раскрывающийся список уже открыт, необходимо щелкнуть два раза.
  2. нет никаких признаков того, что это раскрывающийся список.
  3. стили не подготовлены должным образом.

Вам не нужно заново изобретать колесо, которое вы используете bootstrap, поэтому старайтесь использовать его как можно чаще.

Проверьте фрагмент:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>


<table class="table table-bordered">
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Email</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@example.com</td>
      <td>
        <div class="dropdown">
          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Add Section
        </button>
          <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
          </div>
        </div>
      </td>
    </tr>
    <tr>
      <td>Mary</td>
      <td>Moe</td>
      <td>mary@example.com</td>
      <td>
      <div class="dropdown">
          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Add Section
        </button>
          <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
          </div>
        </div>
      </td>
    </tr>
    <tr>
      <td>July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
      <td>
      <div class="dropdown">
          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Add Section
        </button>
          <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...