动画scrollTop无法在Chrome上运行?

时间:2017-04-21 22:23:23

标签: javascript css google-chrome

我使用这样的锚元素:

<div class="my_centered" id="index_scroll_down_button">
    <a href="#" onclick="smooth_scroll('#intro')">
        <img src="/static/img/scroll-down-icon.png">
    </a>
</div>

<div class="indexcontainer container" id="intro"> 
</div>

其中smooth_scroll函数定义为:

function smooth_scroll(target){
    $('html, body').animate({
        scrollTop: $(target).offset().top - 60
    }, 800);
}

这种方法在Safari上运行良好,但似乎无法在Chrome上运行? 这是我的css:

#index_scroll_down_button {
   position: absolute;
   bottom: 0px;
   left: 50%;
   margin-left: -30px;
}

2 个答案:

答案 0 :(得分:2)

Animate scrolltop在firefox中为我工作,但在chrome和edge中没有。以下css导致了这个问题:

html, body {
    overflow-x: hidden;
}

答案 1 :(得分:1)

脚本运行正常,但您必须阻止默认的锚点击事件,在您的情况下使用:

<a href="#" onclick="smooth_scroll('#intro'); return false;">

但是,请尝试删除嵌入的脚本并执行以下操作:

&#13;
&#13;
$('[data-scrollto]').on('click', function(e) {
    e.preventDefault();
    var target = $( $(this).data('scrollto') );
    $('html, body').animate({
        scrollTop: target.offset().top - 60
    }, 800);
});
&#13;
#intro {
    border-bottom: 1px solid black;
}
#content {
    height: 1000px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="intro">
    Intro
</div>
<div id="content">
    Content height 1000px.
</div>
<div class="my_centered" id="index_scroll_down_button">
    <a href="#" data-scrollto="#intro">
        Scroll top
    </a>
</div>
&#13;
&#13;
&#13;

同样在JSFiddle