首页 > 解决方案 > 带有平滑滚动效果的粘滞标题封面内容

问题描述

我添加了一个粘性标题和平滑的滚动效果,但我无法弄清楚如何固定位置,因此它与标题大小有关。我尝试过的东西完全禁用了粘性标题。

我尝试使用几种不同的技术,尽管我是新手,我自己可能很难做到。

<div id="container">
  <section id="sectionHome">
    <!--Header and Logo-->
    <header id="myHeader">
      <logo>
        <img src="Pictures/Marvel-logo-880x660.crop.png">
      </logo>
    </header>

    <!--The Top Navigation Menu-->
    <div id="mainNav">
      <ul>
        <li class="current"><a href="#">Home</a></li>
        <li><a href="#firstArticle">Characters</a></li>
        <li><a href="#secondArticle">Movies</a></li>
        <li><a href="#thirdArticle">More Info</a></li>
      </ul>
    </div>
  </section>
//Smooth Scrolling in Main Nav
$(document).ready(function() {
  $('#mainNav li a').click(function(e) {

    var targetHref = $(this).attr('href');

    $('html, body').animate({
      scrollTop: $(targetHref).offset().top
    }, 1000);

    e.preventDefault();
  });
});


// Sticky Header
window.onscroll = function() {
  myFunction()
}; // When the user scrolls the page
var header = document.getElementById("sectionHome"); // Get the header and top nav
var sticky = header.offsetTop; // Get the offset position of the navbar
function myFunction() { // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

这是我尝试过的一件事,但它禁用了我的粘性标题:

$(document).ready(function() {

  var headerHeight = $('header').outerHeight(); // Target your header navigation here

  $('#main-nav li a').click(function(e) {

    var targetHref   = $(this).attr('href');

    $('html, body').animate({
        scrollTop: $(targetHref).offset().top - headerHeight // Add it to the calculation here
    }, 1000);

    e.preventDefault();
  });
});

我想我可以为总标题大小设置一个值并以这种方式定位它,尽管它禁用了粘性标题。我该如何正确地做到这一点?

这是我的网页: http: //www.student.city.ac.uk/~aczc972

最好的问候,丹妮尔

标签: javascriptheaderstickyscroll-position

解决方案


我已经添加了一个沙箱,如何使用 jQuery 来完成它,一般来说,我的站点中只有一个添加是我正在检查目标是什么,例如滚动到首页,如果是,我正在为它运行指定的代码:

if (targetHref === "#") {
  $("html, body").animate(
    { scrollTop: 0 },
    "1000"
  );
} else {
  $("html, body").animate({scrollTop: $(targetHref).offset().top},1000);
}

codeandbox.io/s/81l87w26w0

减去标题高度滚动以防止标题覆盖内容

scrollTop: $(targetHref).offset().top - 180"

推荐阅读