平滑滚动仅适用于同一页面,而不适用于外部链接

时间:2014-11-20 12:49:44

标签: javascript jquery

我将此代码用于wordpress付费主题(Gavick - Creativity),并使用以下代码:

 jQuery(document).ready(function () {
    // SmoothScroll jQUery substitue
    jQuery('a[href^="#"]').click(function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = jQuery(target);

        if ($target.length) {
            jQuery('html, body').stop().animate({
                'scrollTop': $target.offset().top + 150
                //'scrollTop': $target.offset().top   ORIGINAL
            }, 1000, 'swing', function () {
               window.location.hash = target+150;
                //window.location.hash = target;  ORIGINAL
            });
        } else {
           window.location.hash = target;
            // window.location.hash = target;   ORIGINAL
        }

    });     

问题在于它只能从内部链接平滑滚动而不是从外部滚动。

当我在同一页面并单击锚链接时,它会完美滚动。 从另一个页面访问页面锚点根本不会滚动。

我需要的只是访问http://domain.com/#anchortag并从页面开头滚动到它。 如果我在同一页面或外部页面中,我还需要能够有不同的偏移量。

任何帮助?

1 个答案:

答案 0 :(得分:0)

首先,

  

从另一个页面访问页面锚点根本不会滚动。

您可以创建一个jQuery函数来检查这种情况:

function checkForAnchor() {
  var pathname = jQuery(location).attr('href');
  pathname = pathname.split("#");

  for(var i = 0; i < pathname.length; i++){
    if(pathname[i] == 'YOUR ANCHOR'){
      jQuery('html, body').animate({ scrollTop: (jQuery('.YOUR CONTAINER TO SCROLL TO').offset().top)}, 'slow');
    }
  }
}
  

如果我在同一页面或外部页面中,我也需要能够有不同的偏移量。

因此您可以使用cookie。当用户首先访问您的页面并且没有cookie时,您可以使用另一个偏移量滚动到。之后设置一个cookie并使用不同的偏移量。