Javascript平滑滚动 - 不能与第二次点击一起使用

时间:2014-03-26 12:14:07

标签: javascript scroll smooth-scrolling

我使用以下脚本获得平滑滚动效果减去一页上的像素数量。问题是,我点击一个锚链接,滚动效果按原样运行,但然后我滚动回到链接所在页面的顶部,然后单击另一个页面。它不起作用。我只是从网页上复制了脚本,我的javascript非常糟糕。

感谢您的帮助。

function filterPath(string) {
    return string
        .replace(/^\//,'')
        .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
        .replace(/\/$/,'');
    }
    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement('html', 'body');

    $('a[href*=#]').each(function() {
        var thisPath = filterPath(this.pathname) || locationPath;
        if (  locationPath == thisPath
        && (location.hostname == this.hostname || !this.hostname)
        && this.hash.replace(/#/,'') ) {
            var $target = $(this.hash), target = this.hash;
            if (target) {
                var targetOffset = $target.offset().top - 70;
                $(this).click(function(event) {
                if(event != 'undefined') {
                    event.preventDefault();}
                    $(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) {
                    e.preventDefault();
                    location.hash = target;
                });
            });
        }
    }
});

function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
        var el = arguments[i],
            $scrollElement = $(el);
        if ($scrollElement.scrollTop()> 0) {
            return el;
        } else {
            $scrollElement.scrollTop(1);
            var isScrollable = $scrollElement.scrollTop()> 0;
            $scrollElement.scrollTop(0);
            if (isScrollable) {
                return el;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

代码中出现错误。

它说:

$(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) {
    e.preventDefault();
    location.hash = target;
});

您正在呼叫preventDefault()。保持原样,它将起作用:

$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
    location.hash = target;
});

答案 1 :(得分:0)

错误发生在代码的开头。您应该向锚元素添加each事件,而不是使用click循环。通过使用each循环,您只需添加一次Click事件,因此在第二次单击时事件为undefined,代码将出现错误。

您的代码重写为click事件:

$('a[href*=#]').click(function(e){
  var thisPath = filterPath(this.pathname) || locationPath;
  if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) {
    var $target = $(this.hash), target = this.hash;
    if (target) {
      var targetOffset = $target.offset().top - 70;
      $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
        if( e != 'undefined' ) {
          e.preventDefault();
        }
        location.hash = target;
      });
    }
  }
});

希望这会有所帮助; - )

相关问题