2017-09-13 29 views
0

如何調整javascript我必須滾動到一個錨點,但也包括一個偏移量。我已經添加了一個偏移200px的規則,但沒有任何效果。如何使用JavaScript爲smoth滾動調整偏移位置?

   $('a[href*="#"]') 
       .not('[href="#"]') 
       .not('[href="#0"]') 
       .click(function(event) { 
       // On-page links 
       if (
        location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
        && 
        location.hostname == this.hostname 
       ) { 
        var target = $(this.hash); 
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
        if (target.length) { 
        event.preventDefault(); 
        $('html, body').animate({ 
         scrollTop: target.offset().top - 200; 
        }, 1000, function() { 
         var $target = $(target); 
         $target.focus(); 
         if ($target.is(":focus")) { 
         return false; 
         } else { 
         $target.attr('tabindex','-1'); 
         $target.focus(); 
         }; 
        }); 
        } 
       } 
      }); 

回答

1

查看下面的代碼片段,瞭解使用jquery的簡單示例。

$('a').click(function(evt) { 
 
    evt.preventDefault(); 
 
    $('html, body').animate({ 
 
    scrollTop: $($(this).attr('href')).offset().top - 50 
 
    }, 800, function() {}); 
 
});
.empty { 
 
    height: 500px; 
 
    width: 100%; 
 
    background: #ccc; 
 
} 
 

 
#content { 
 
    height: 200px; 
 
    width: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#content">Click Me!</a> 
 
<div class="empty"></div> 
 
<div id="content"> 
 
    Content goes here.! 
 
</div> 
 
<div class="empty"></div>