Как сделать скрол через якорь и отодвинуть страницу вверх?

У меня сайт, с шапкой pos: fixed, я хочу при клике в шапке на "Условия", например, кидать пользователя на якорь этого блока и отодвигать всю страницу вверх на высоту шапки, иначе часть блока находится под шапкой. Вот ссылка на сайт https://q1zin.ru/globalus/


Ответы (1 шт):

Автор решения: Vasiliy Rusin

Примеры не будут работать в песочнице SO.

Вариант 1. scrollIntoView

Использовать метод scrollIntoView.

window.scrollIntoView({
    block: "start",
    alignToTop: true,
    behavior: "smooth"
});

Так же нужно добавить scroll-padding-top к html тегу, с указанием высоты вашего header.

html {
  scroll-padding-top: $header-height;
}

Пример на jsFiddle.

window.addEventListener("DOMContentLoaded", function () {
    const header = document.querySelector('.header');
    const headerHeight = header.offsetHeight;

    document.querySelectorAll('.anchor[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            const element = document.querySelector(this.getAttribute('href'));

            element.scrollIntoView({
                block: "start",
                alignToTop: true,
                behavior: "smooth"
            });
        });
    });
})
html,
body {
  margin: 0;
  font-family: sans-serif;
}

html {
  scroll-padding-top: 60px;
}

main {
  padding-top: 60px;
}

.header {
  width: 100%;
  height: 60px;
  position: fixed;
  background-color: whitesmoke;
}

.navigation {
  height: 100%;
}

.menu {
  margin: 0;
  padding: 0;
  height: 100%;
  display: flex;
  list-style: none;
  align-items: center;
}

.menu-item {
  flex: 1;
  text-align: center;
}

.section {
  width: 100%;
  height: 100vh;
}

.section.center {
  display: flex;
  justify-content: center;
}

.slider {
  color: white;
  background-color: #4fc3f7;
}

.news {
  color: white;
  background-color: #aed581;
}

.contacts {
  color: white;
  background-color: #e57373;
}
<header class="header">
    <nav class="navigation">
        <ul class="menu">
            <li class="menu-item">
                <a href="#news" class="anchor">
                    news
                </a>
            </li>
            
            <li class="menu-item">
                <a href="#contacts" class="anchor">
                    contacts
                </a>
            </li>
        </ul>
    </nav>
</header>

<main>
    <header class="section center slider">
        <h1>
            slider
        </h1>
    </header>
    
    <section id="news" class="section center news">
        <h1>
            news
        </h1>
    </section>
    
    <section id="contacts" class="section center contacts">
        <h1>
            contacts
        </h1>
    </section>
</main>

Вариант 2. scrollTo

Использовать метод scrollTo.

window.scrollTo({
    top,
    behavior: "smooth"
});

Пример на jsFiddle.

window.addEventListener("DOMContentLoaded", function() {
  const header = document.querySelector('.header');
  const headerHeight = header.offsetHeight;

  document.querySelectorAll('.anchor[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      e.preventDefault();

      const element = document.querySelector(this.getAttribute('href'));

      window.scrollTo({
        top: element.offsetTop - headerHeight,
        behavior: "smooth"
      });
    });
  });
})
html,
body {
  margin: 0;
  font-family: sans-serif;
}

main {
  padding-top: 60px;
}

.header {
  width: 100%;
  height: 60px;
  position: fixed;
  background-color: whitesmoke;
}

.navigation {
  height: 100%;
}

.menu {
  margin: 0;
  padding: 0;
  height: 100%;
  display: flex;
  list-style: none;
  align-items: center;
}

.menu-item {
  flex: 1;
  text-align: center;
}

.section {
  width: 100%;
  height: 100vh;
}

.section.center {
  display: flex;
  justify-content: center;
}

.slider {
  color: white;
  background-color: #4fc3f7;
}

.news {
  color: white;
  background-color: #aed581;
}

.contacts {
  color: white;
  background-color: #e57373;
}
<header class="header">
  <nav class="navigation">
    <ul class="menu">
      <li class="menu-item">
        <a href="#news" class="anchor">
                    news
                </a>
      </li>

      <li class="menu-item">
        <a href="#contacts" class="anchor">
                    contacts
                </a>
      </li>
    </ul>
  </nav>
</header>

<main>
  <header class="section center slider">
    <h1>
      slider
    </h1>
  </header>

  <section id="news" class="section center news">
    <h1>
      news
    </h1>
  </section>

  <section id="contacts" class="section center contacts">
    <h1>
      contacts
    </h1>
  </section>
</main>

→ Ссылка