Остановить плавную прокрутку между разделами в среднем положении

У меня есть следующий структурированный код. У меня есть липкий заголовок, а также несколько разделов на моей странице. У меня есть несколько гиперссылок на странице.

Как вы можете видеть во фрагменте, внутри раздела 1 и раздела 2 есть текст ссылки.

Я добавил jquery из w3school для плавной прокрутки.


ПРОБЛЕМА

Когда гиперссылка нажата, она прокручивается до раздела 2 и занимает начальную точку раздела 2 в верхней части тела. Поскольку у меня липкий заголовок, он скрывает часть содержимого раздела 2.

ЧЕГО Я ХОЧУ СЕЙЧАС. При прокрутке к разделу 2 я хочу, чтобы раздел начинался после липкого заголовка, а не начинался в верхней части тела.

// Add smooth scrolling to all links
$("a").on('click', function(event) {

  // Make sure this.hash has a value before overriding default behavior
  if (this.hash !== "") {
    // Prevent default anchor click behavior
    event.preventDefault();

    // Store hash
    var hash = this.hash;

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $(hash).offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
      window.location.hash = hash;
    });
  } // End if
});
header {
  background: red;
  width: 100%;
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

#sec-1,
#sec-2 {
  width: 100%;
  height: 100vh;
}

#sec-1 {
  margin-top: 50px;
  background: green;
}

#sec-2 {
  background: blue;
}

#sec-2>p {
  background: #fff;
  margin: auto;
  width: 60%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header></header>

<section id="sec-1">
  <a href="#sec-2">Scroll to section 2</a>
</section>
<section id="sec-2">
  <p>This is section 2</p>
</section>


person Ramesh    schedule 21.09.2018    source источник
comment
добавить смещение. Ваша верхняя часть прячется за полосой прокрутки, поэтому вам нужно смещение на ней с высотой вашей полосы заголовка.   -  person Dorvalla    schedule 21.09.2018
comment
Я пробовал scrollTop: $(hash).offset().top + 70, но это не помогло. На самом деле мне нужно, чтобы 70 пикселей были перемещены сверху.   -  person Ramesh    schedule 21.09.2018


Ответы (3)


Ваша проблема - последняя строка в javascript.

/ Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash;

Это фактически заставляет ваш URL перейти к исходной позиции хеша. На самом деле вы не добавляете #, но вы заставляете окно перейти к вашему оригиналу, определенному в переменной javascript hash, которая в данном случае section-2.

// Add smooth scrolling to all links
$("a").on('click', function(event) {

  // Make sure this.hash has a value before overriding default behavior
  if (this.hash !== "") {
    // Prevent default anchor click behavior
    event.preventDefault();

    // Store hash
    var hash = this.hash;

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $(hash).offset().top -70
    }, 800, function() {

    });
  } // End if
});

Прокрутка теперь работает как положено.

https://jsfiddle.net/exuj6mro/18/

person Dorvalla    schedule 21.09.2018
comment
вместо 70; вы можете минус динамическая высота заголовка. - person Divyesh Prajapati; 21.09.2018
comment
правда, но я взял 70, как ОП определил это по комментариям. - person Dorvalla; 21.09.2018

Вам нужно удалить высоту заголовка из прокрутки;

$('html, body').animate({
  scrollTop: $(hash).offset().top - $('header').height()
}, 800, function() {

  // Add hash (#) to URL when done scrolling (default click behavior)
  window.location.hash = hash;
});
person Divyesh Prajapati    schedule 21.09.2018
comment
Спасибо @Рамеш - person Divyesh Prajapati; 21.09.2018

сначала вам нужно вычесть высоту заголовка из смещения scrollTop в блоке анимации.

во-вторых, когда вы используете window.location.hash, это вызывает настоящую проблему, когда window.location.hash срабатывает, страница снова прокручивается для гиперссылки (как в традиционном поведении гиперссылок). Приведенный ниже код работает должным образом, надеюсь, он решит вашу проблему.

// Add smooth scrolling to all links
$("a").on('click', function(event) {

  // Make sure this.hash has a value before overriding default behavior
  if (this.hash !== "") {
    // Prevent default anchor click behavior
    event.preventDefault();

    // Store hash
    var hash = this.hash;

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: parseInt($(hash).offset().top - parseInt($('header').height()))
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
      // window.location.hash = hash;
    });
  } // End if
});
header {
  background: red;
  width: 100%;
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

#sec-1,
#sec-2 {
  width: 100%;
  height: 100vh;
}

#sec-1 {
  margin-top: 50px;
  background: green;
}

#sec-2 {
  background: blue;
}

#sec-2>p {
  background: #fff;
  margin: auto;
  width: 60%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header></header>

<section id="sec-1">
  <a href="#sec-2">Scroll to section 2</a>
</section>
<section id="sec-2">
  <p>This is section 2</p>
</section>

person Nikhil Kinkar    schedule 21.09.2018