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

#jquery #scrolltop

#jquery #scrolltop

Вопрос:

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

https://jsfiddle.net/t2fpeq0d/

 $('.accordion-block-heading').on('click', function() {
  var $this = $(this);
  var $parent = $this.parent();
  var $position = $this.position().top;
  console.log($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 -->  

Ответ №1:

Вы можете использовать Position следующим образом:

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

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

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

Комментарии:

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

Ответ №2:

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

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

Проверьте этот обновленный JS Fiddle

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

Комментарии:

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

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