簡體   English   中英

Javascript平滑滾動-不適用於第二次單擊

[英]Javascript Smooth Scrolling - Not working with second click

我使用以下腳本來實現平滑的滾動效果,從而減少一頁上的像素數量。 問題是,我單擊一個錨鏈接,滾動效果應按預期工作,但隨后我滾動回到鏈接所在頁面的頂部,然后單擊另一頁。 它不起作用。 我只是從網頁上復制了腳本,但是我的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;
            }
        }
    }
}

代碼中有錯誤。

它說:

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

您什么都沒有調用preventDefault() 保留它,它將起作用:

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

錯誤出現在代碼的開頭。 您應該在錨元素中添加click事件,而不是使用each循環。 通過使用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;
      });
    }
  }
});

希望這可以幫助 ;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM