锚点动画滚动不准确

anchor animation scroll is not accurate

我碰巧放置在战略位置以访问锚点滚动浏览网站。它做了一个动画 jquery 但大多数时候或达不到或超过了那个地方,不知道因为它在网站上不是 100% 准确,会发生什么?

jquery:

$(function(){

     $('a[href*=#]').click(function() {

     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) {

                 var targetOffset = $target.offset().top;

                 $('html,body').animate({scrollTop: targetOffset}, 1000);

                 return false;

            }

       }

   });

});

按钮:

<a id="ancla-1" href="#ancla-1">

<a name="ancla-1"></a>

最后我找到了问题,我把它放在这里,以防有人能给他解决方案。

页面加载速度如此之快,以至于没有考虑到使用页眉的 space。解决方案是应用一个计时器,它需要一秒钟来激活页面的滚动。

也许这不是一个非常优雅的解决方案,但这种方式永远不会失败。

$(document).ready(function() {

setTimeout(function () {
    var anchor = window.location.hash.substring(1);

if(anchor!="" || anchor!="AB"){

    var newAnchor= "#anchor-" +anchor;

    $(newAnchor).trigger("click");

}

    }, 1000);


});