Anchor Smooth Scroll Script跳跃

时间:2014-12-10 15:10:14

标签: javascript jquery html

我正在尝试使用JS实现平滑滚动,但是我从锚定点获得的是一个急剧跳跃,而不是平滑过渡。这是代码,我很确定我的语法是正确的,虽然显然没有,因为它不起作用。我试图链接的两个元素,加上脚本。

  <div id="crumbs1">
   <a href="#anchor1"></a>
   </div>


'<div class="poem">
<div id="poem-list1">
<a href="/Crows">Black Crows</a>
<a name="anchor1" id="anchor1"></a>
</div>'

`$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 1000);
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

如果你没有(绝对)必须使用锚点(并且你可以控制KID),你可以尝试类似的东西:

(HTML)

<div id="q1" class="question"><p id="p1" class="dp1">Anchor 1</p></div>
<div id="q2" class="question"><p id="p2" class="dp2">Anchor 2</p></div>
<div id="q3" class="question"><p id="p3" class="dp3">Anchor 3</p></div>

<div id="r1" class="result"><p id="" class="">Response 1</p></div>
<div id="r2" class="result"><p id="" class="">Response 2</p></div>
<div id="r3" class="result"><p id="" class="">Response 3</p></div>

和 (脚本)

$('div[id*=q]').click(function () {

var $this = $(this).attr('id');
var $nmb = $this.substr(1);
var $target = 'r' + $nmb;

    if ($target.length) {

        var $target = '#' + $target;
        var thisTarget = $($target).offset().top;

        $('html,body').animate({
            scrollTop: thisTarget
        }, 1000);
        return false;
    }

});
相关问题