jquery在单个hash锚点上平滑滚动以获得顶部



我使用这个jquery平滑滚动函数:

$('a[href*=#]').on('click',function(event){
//event.preventDefault(); // nope
$('html,body').animate({scrollTop:$(this.hash).offset().top},500); 
});

当点击锚链接时,它可以完美工作:

<a href="#section1">smooth scroll</a>

除非点击一个散列返回顶部,比如:

<a href="#">home</a>

在这种情况下,我看到了页面的顶部,但没有平滑的滚动效果。。

我知道,如果链接调用页面上第一个元素的id,一切都会正常工作,只是想知道是否有一种方法可以使用单个哈希在顶部上平滑地scrool

我建议在部分添加一个锚点数据锚点offset="30",并检查锚点。根据您的情况,将使用defaultAnchorOffset。在此处进行工作演示:http://jsfiddle.net/v4tzngmr/

$('a[href*=#]').on('click',function(event){
     event.preventDefault();
    var defaultAnchorOffset = 0;
    var $anchor = $('#' + this.hash.substring(1));
    var anchorOffset = $anchor.data('anchor-offset');
    if (!anchorOffset) // for when anchor doesn't have the offset attribute like Section 4
    anchorOffset = defaultAnchorOffset;
    var offset = $anchor.offset() === undefined ? 0 : $anchor.offset().top;
    $('html,body').animate({
        scrollTop: offset - anchorOffset
    }, 500);
});

您可以将一个类添加到链接.gotop中,它就会工作。您将添加0到scrollTop,它将转到页面顶部:)

$('.gototop').on('click', function (event) {
    event.preventDefault();
    $('html,body').animate({
        scrollTop: 0
    }, 500);
});

您的代码不起作用,因为如果在散列之后不添加元素的ID,它将不会获得元素的偏移量$(this.hash)与$("#diver")相同,并且将选择ID为diver的元素,并且由于在#之后没有给出任何内容,因此它将不会接收到用于搜索偏移量的元素,从而导致错误。如果你检查你的控制台,它会显示这个:

未捕获类型错误:无法读取未定义的属性"top":)

Giannis Grivas的回答连接到StackOverflow 的其他几个解决方案

Nota-bene:我是JQuery的总假人。我只连接了几个解决方案,它很有效!

HTML:

<a href="#section1">smooth scroll</a>
<a href="#">home</a>

JQUERY:

$(function() {
        $('a[href*="#"]').click(function() {
            if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname) {                    
                var defaultAnchorOffset = 0;
                var $anchor = $('#' + this.hash.substring(1));
                var anchorOffset = $anchor.data('anchor-offset');
                var href = $.attr(this, 'href');                    
                if (!anchorOffset)
                    anchorOffset = defaultAnchorOffset;
                var offset = $anchor.offset() === undefined ? 0 : $anchor.offset().top;
                $('html, body').animate({
                  scrollTop: offset - anchorOffset
                  }, 500, 
                    function () {
                      window.location.hash = href;
                    }
                  );
                return false;
            }
        });
    });

最新更新