javascript - 我的粘性标题覆盖具有平滑滚动效果的内容

标签 javascript header sticky scroll-position

我添加了粘性标题和平滑滚动效果,但我不知道如何修复位置,以便它与标题大小一起计算。我尝试过的事情完全禁用了粘性标题。

我尝试过使用几种不同的技术,尽管我是新手,而且对我自己来说可能太难了。

<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

最诚挚的问候, 丹妮尔

最佳答案

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

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

codesandbox.io/s/81l87w26w0

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

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

关于javascript - 我的粘性标题覆盖具有平滑滚动效果的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455445/

相关文章:

javascript - 单击提交按钮时,临时更改 PHP 中同一页面上的 HTML 结构?

javascript - 三.js ParametricGeometry动画(动态变化功能)

html - W3C 验证 - 为什么 &lt;header&gt; 标签不被接受?

当提交按钮被禁用时,PHP 重定向不起作用

node.js - Nodejs如何为每个请求设置内容类型 header

javascript - 在 NodeJS 中下载时无法获取文件的哈希值

javascript - 批量 REST API POST 处理

javascript - 如何删除粘性 header 并使其保持静态

html - 当遇到 float 内容时粘性导航会中断?

css - 无法使 CSS Sticky 页脚正常工作。我究竟做错了什么?