从另一页减去 X 距离滚动到特定 div

Scroll to specific div from another page minus X distance

我正在使用以下脚本来执行标题中描述的操作。

    <script type="text/javascript">
              var jump=function(e)
      {
         if (e){
             e.preventDefault();
             var target = $(this).attr("href");
         }else{
             var target = location.hash;
         }

         $('html,body').animate(
         {
             scrollTop: $(target).offset().top
         },1000,function()
         {
             location.hash = target;
         });

      }

      $('html, body').hide();

      $(document).ready(function()
      {
          $('a[href^=#]').bind("click", jump);

          if (location.hash){
              setTimeout(function(){
                  $('html, body').scrollTop(0).show();
                  jump();
              }, 0);
          }else{
              $('html, body').show();
          }
      });
      </script> 

它工作得很好。但是,我有一个固定的 header ,一旦滚动到 div 就会覆盖它。我想从所需的滚动目标减去 80px。我该如何修改代码来执行此操作?

这是现场版。

robertkoh.net/Electrotemp/index.html

点击 'ducted vacuum systems'。它会将您带到产品和服务页面并滚动到相应的部分。如您所见,固定的 header 覆盖了它的一部分。

方案一:减去80像素不重新设置location.hash

您只需更改此块:

 $('html,body').animate({
     scrollTop: $(target).offset().top
 }, 1000, function() {
     location.hash = target;
 });

进入如下代码:

 $('html,body').animate({
     scrollTop: $(target).offset().top - 80
 }, 1000);
  • 添加的 - 80 会减去这 80 个像素,因此滚动会提前停止。
  • 删除location.hash = target;(在滚动动画完成后调用)修复了跳回旧位置的问题。此代码重新设置哈希标签,导致浏览器再次向后滚动。但请注意,单击站点内部哈希链接不会再更新 URL 栏中的哈希。

解决方案 2:将您的页面内容移动到单独的可滚动文件中 <div>

  • 创建一个在 <!--end slideMenu--> 之后开始并在 </body> 之前结束的新 <div id="container">
  • 将行 $('html,body').animate({ 更改为 $('#container').animate({
  • .titlebar 中删除 margin-top: 70px;
  • #container 元素添加此 CSS:

    #container {
        position: fixed;
        top: 70px;
        bottom: 0;
        left: 0;
        overflow: auto; /* enable scrolling */
    }
    

这样做有一些好处:

  • 您不必添加 - 80
  • 您不必删除 location.hash = target;
  • 未启用 JavaScript 的浏览器会跳转到正确的位置。