函数goToNext上的平滑滚动+偏移

时间:2013-12-10 02:04:25

标签: javascript jquery scroll offset smooth-scrolling

我想从顶部添加偏移并平滑滚动到以下功能, 该功能位于一个固定的按钮上,并跟随用户进入页面。此按钮必须能够滚动多个锚点然后返回到第一个锚点,理想情况下从顶部开始偏移105px。在网上拖了几个小时寻求帮助,没有让jquery知道自己如何解决这个问题,任何帮助? 这里的类似示例 - http://www.google.com/nexus/7/(右下角的按钮)

<script>
var max = 6;

function goToNext() {
    var hash = String(document.location.hash);
    if (hash && hash.indexOf(/anchor/)) {
        var newh = Number(hash.replace("#anchor",""));
        (newh > max-1) ? newh = 0 : void(null);
        document.location.hash = "#anchor" + String(newh+1); 
    } else {
        document.location.hash = "#anchor1";        
    }
}

</script>
<a href="#" onclick="goToNext();return false;"></a>

<div id="anchor1"></div>
<div id="anchor2"></div>
<div id="anchor3"></div>
<div id="anchor4"></div>
<div id="anchor5"></div>
<div id="anchor6"></div>

1 个答案:

答案 0 :(得分:3)

您可以使用animate({scrollTop:value},delay)顺利滚动到元素。

$('document').ready(function () {
     //on DOM ready change location.hash to 'anchor1'
     window.location.hash = 'anchor1';
    //GO TO NEXT click event:
    $('a').click(function (e) {
        //preventing the default <a> click (href="#")
        e.preventDefault();
        //get the current hash to determine the current <div> id 
        var hash = window.location.hash,
            //find the (next) immediate following sibling of the current <div>
            $next = $(hash).next('div');
        //check if this next <div> sibling exist
        if ($next.length) {
            var id = $next.attr('id'),
                nextOffsetTop = $next.offset().top;
            //animate scrolling and set the new hash
            $('body, html').animate({scrollTop: nextOffsetTop}, 'slow');
            window.location.hash = id;
        }else{
        //else if the next <div> sibling does not exist move to the first anchor
            var first = '#anchor1';
            $('body, html').animate({scrollTop: $(first).offset().top},'slow');
            window.location.hash = first;
        }

    });
})

请参阅此jsfiddle


然后是 闪烁 。实际上,如果仔细查看上面的代码,它不会闪烁,但有些生涩。我先设置animate(scrollTop),然后更改哈希window.location.hash = id。现在,当动画开始滚动时,突然我们正在更改哈希,它往往会直接跳到下一个<div>(这是默认的haschange事件),但是被animate()拉回来了导致滚动生涩

我们不能只停止haschange事件的默认传播,可能有一个解决方案可以做到这一点,但不能保证它可以在所有浏览器上工作,每个浏览器在{{{{{{{ 1}}事件。但是,由于@Andy E在您提供的SO帖子上的解决方案,我们不需要停止转换传播。我们可以先简单地更改哈希值,将其重置为最后haschange位置,然后随意动画滚动!

scrollTop()

检查此更新的jsfiddle


现在让我们谈谈HTML5 History API。我之所以没有首先介绍这个原因,是因为它在HTML5(尤其是IE)浏览器中的实现方式不同,并且没有HTML4浏览器的后备,这使得这种方法在某种程度上不一致。但是你可以使用插件正确地完成这项工作。

以下是使用//get the current scrollTop value var st = $(window).scrollTop(); //change the hash window.location.hash = id; //reset the scrollTop $(window).scrollTop(st); //animate scrolling $('body, html').animate({scrollTop: nextOffsetTop}, 'slow');

进行操作的方法
history.pushState()

请参阅此jsfiddle

那就是它。干杯!