简体   繁体   English

为什么我的平滑滚动不能正常工作?

[英]Why does my smooth scroll not work properly?

I tried several different ways to scroll smoothly to the top.我尝试了几种不同的方法来平滑滚动到顶部。

I've used this code and some others, a specially for the #top attribute, but nothing seems to work.我已经使用了这段代码和其他一些代码,专门用于#top属性,但似乎没有任何效果。

Where did I go wrong?我哪里做错了?

<!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>

Include CDN version of jQuery library包含 CDN 版本的jQuery 库

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

in your <head> section.在您的<head>部分。

Or Download jQuery library and use a local copy.下载 jQuery 库并使用本地副本。

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

If you using local copy don't forget to put jquery-1.10.2.min.js in your root folder.如果您使用本地副本,请不要忘记将jquery-1.10.2.min.js放在您的根文件夹中。


Also you can simplify your function您也可以简化您的功能

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

I agree with the other posts to add jQuery (your example didn't source it).我同意添加 jQuery 的其他帖子(您的示例没有提供它)。 Also, for smoother animations/transitions you may want to try using CSS transitions opposed to JS animations.此外,为了更流畅的动画/过渡,您可能想尝试使用 CSS 过渡而不是 JS 动画。

Here is a tutorial on CSS transitions to smooth scroll to the top using jQuery.这是一个关于使用 jQuery 平滑滚动到顶部的 CSS 过渡教程。

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

Also, I personally am a huge fan of the jQuery transit library which uses jQuery to trigger all kinds of CSS transitions.此外,我个人是 jQuery 传输库的忠实粉丝,它使用 jQuery 触发各种 CSS 转换。

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

For more information on why CSS transitions are better than JS library animation effects please see this thread .有关为什么 CSS 过渡优于 JS 库动画效果的更多信息, 请参阅此线程

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM