2017-04-21 101 views
0

我用这样一个锚元素:Animate scrollTop在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; 
} 
+0

工作正常https://codepen.io/anon/pen/YVWqrG –

回答

1

脚本运行良好,但你要防止默认锚点击事件,在您的情况下使用:

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

但是,请尝试删除嵌入式脚本做这样的事情:

$('[data-scrollto]').on('click', function(e) { 
 
    e.preventDefault(); 
 
    var target = $($(this).data('scrollto')); 
 
    $('html, body').animate({ 
 
     scrollTop: target.offset().top - 60 
 
    }, 800); 
 
});
#intro { 
 
    border-bottom: 1px solid black; 
 
} 
 
#content { 
 
    height: 1000px; 
 
}
<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>

也在JSFiddle

+0

感谢您的评论......在你的榜样,你有两个ID与介绍,这可能会导致一些麻烦。我无法在Chrome中正常工作。我复制了你的例子,但它只适用于Safari浏览器?你也可以说几句话,你为什么喜欢你的点击事件,而不是我的功能? – carl

+0

我删除了第二个#intro,从上面的示例代码复制/粘贴,应该在Chrome中工作。我们应该避免设置内联脚本,样式相同,都应该在远程文件中设置。我们应该用class,id或data属性来标记元素,然后决定如何处理它。这种方式的变化很容易,我们可以做可重用的脚本。但是,这只是一个评论,你的麻烦的关键是防止默认锚定点击行动,对于本地链接是跳转/滚动到元素。 – skobaljic

1

Animate scrolltop在firefox中为我工作,但不在铬和边缘。下面的CSS问题造成的:

html, body { 
    overflow-x: hidden; 
} 
+0

那么删除这一点解决了这个问题?看起来他们的代码中没有这样的CSS。请确保你回答了问题,否则预计会添加评论。最好的问候 – YakovL

+0

这个答案现在帮了我,谢谢。 – nanuqcz

相关问题