ScrollTop внутри полосы прокрутки css (overflow-y: auto)

Я работаю над этим аккордеоном. Здесь вы можете увидеть список аккордеонов внутри полосы прокрутки. Здесь всякий раз, когда мы нажимаем на заголовок, он должен прокручиваться вверх, чтобы заголовок и текст были видны правильно. Я пробовал много вещей, но это не работает внутри полосы прокрутки. Хотя код находится совершенно снаружи, где у нас нет полосы прокрутки. Вот рабочий пример, которую я создал. Надеюсь, кто-нибудь поможет.

https://jsfiddle.net/t2fpeq0d/

$('.accordion-block-heading').on('click', function() {
  var $this = $(this);
  var $parent = $this.parent();
  var $position = $this.position().top;
  console.info($position);
  $this.next().stop().slideToggle();

  $('.site-accordion').animate({
    scrollTop: $this.offset().top
  }, 2000);


});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML-


<!-- Site Accordion -->
<ol class = "site-accordion mt-30">
  <!-- Accordion Block -->
  <li class = "accordion-block">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block`enter code here`">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block" id = "test">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
  <!-- Accordion Block -->
  <li class = "accordion-block last-block" style = "padding-bottom: 0">
    <h3 class = "accordion-block-heading">Title question goes here lorem ipsum dolor?</h3>
    <p class = "accordion-block-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </li>
  <!-- Accordion Block -->
</ol>
<!-- Site Accordion -->
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
1
0
38
2

Ответы 2

Вы можете использовать Позиция, например:

$("body, html").animate({
    scrollTop: $("#accordian-block-1").position().top
});

Очевидно, вам нужно добавить уникальный идентификатор к каждому элементу.

Я бы рекомендовал использовать .attr() для получения идентификатора любого заголовка, по которому щелкнули, а затем преобразовать идентификатор заголовка в число. Затем вы можете использовать этот номер для предоставления идентификатора нужного элемента/аккордеонного блока для прокрутки.

Проверьте еще раз, пожалуйста. Мой CSS не обновлялся там. Из-за этого не было полосы прокрутки. Теперь я добавил его, и вы видите, что он не работает.

Nishant Sharma 28.03.2019 17:04

Вы пытаетесь расположить элемент site-accordion в верхней части нажатого аккордеона. Вы должны позиционировать тело документа в элементе аккордеона следующим образом:

$([document.documentElement, document.body]).animate({
    scrollTop: $position
}, 2000);

Проверьте этот обновленный JS Скрипка

Прошу прощения за орфографические ошибки, отвечаю с мобильного устройства.

Проверьте еще раз, пожалуйста. Мой CSS не обновлялся там. Из-за этого не было полосы прокрутки. Теперь я добавил его, и вы видите, что он не работает.

Nishant Sharma 28.03.2019 17:04

Привет, Нишант, где именно ты добавил свой CSS? Я не вижу никакого CSS в скрипке, присутствующей в вашем вопросе? Вы создали новую скрипку? Если да, то не могли бы вы дать ссылку на него?

user3613129 29.03.2019 06:02

Другие вопросы по теме