【问题标题】:Why does my smooth scroll not work properly?为什么我的平滑滚动无法正常工作?
【发布时间】:2013-12-31 13:49:54
【问题描述】:

我尝试了几种不同的方式来平滑滚动到顶部。

我已经使用了这段代码和其他一些代码,专门用于 #top 属性,但似乎没有任何效果。

我哪里做错了?

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Naamloos document</title>

<link href="basis.css" rel="stylesheet" type="text/css">
<link href="navigatie/menu.css" rel="stylesheet" type="text/css">
<script>$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});</script>

</head><body>

<div id="header">
  <a href="#top"><img src="navigatie/bb.png" alt="" width="100" height="100" id="Image1"></a>
</div>

blabla content

</body>
</html>

【问题讨论】:

  • 检查控制台是否有错误。
  • 我们是否假设您已经检查了 $("#top") 元素存在并且被您的查询找到?您是否还试图分别触发 html 和 body 上的滚动?这种重复有什么原因吗?有机会发布 jsFiddle。

标签: javascript html css


【解决方案1】:

包括jQuery library的CDN版本

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

在您的 &lt;head&gt; 部分中。

Download jQuery library 并使用本地副本。

<script src="jquery-1.10.2.min.js"></script>

如果您使用本地副本,请不要忘记将jquery-1.10.2.min.js 放在您的根文件夹中。


你也可以简化你的功能

$(function() {
  $('#header a').click(function() {
    $('html, body').stop().animate({ scrollTop: $($(this).attr('href')).offset().top }, 900, 'swing'); 
  });
});

【讨论】:

  • 这会有所帮助。还要确保一些 ID 为 top 的元素存在。
【解决方案2】:

我同意添加 jQuery 的其他帖子(您的示例没有提供它)。此外,对于更流畅的动画/过渡,您可能需要尝试使用与 JS 动画相反的 CSS 过渡。

这是一个使用 jQuery 平滑滚动到顶部的 CSS 过渡教程。

http://mitgux.com/smooth-scroll-to-top-using-css3-animations

另外,我个人是 jQuery 传输库的忠实粉丝,它使用 jQuery 来触发各种 CSS 转换。

http://ricostacruz.com/jquery.transit/

更多关于为什么 CSS 过渡比 JS 库动画效果更好的信息please see this thread

祝你好运!

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多