简体   繁体   English

平滑滚动到顶部不起作用

[英]smooth scrollTo top not working

I am making a div which on press sends the user to the top but with a smooth scroll. 我正在制作一个div,按此按钮会将用户带到顶部,但滚动平滑。 I am able to send it to the top but not with the smooth scroll. 我能够将其发送到顶部,但不能平滑滚动。

My code is below 我的代码如下

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
      $(document).ready(function(){
            $('#footer a').click(function () {
            $('body,html').animate({scrollTop:0},1000);
      return false;
      };
      }

</script>

You made some mistakes in the syntax. 您在语法上犯了一些错误。 Try this: 尝试这个:

$(document).ready(function() {
    $('#footer a').click(function(){
         $("html, body").animate({ scrollTop: 0 }, 1000);
         return false;
    });
});

The scrollTop:0 scrolls to the very top of the page, at 0px position, and the 1000 represents the duration of animation in milliseconds. scrollTop:0滚动到页面的顶部,在0px的位置,而1000表示动画的持续时间(以毫秒为单位)。 The Higher values indicate slower animations. 较高的值指示较慢的动画。 You can also use 'fast', 'slow' or 'normal' instead of milliseconds. 您还可以使用“快速”,“缓慢”或“正常”而不是毫秒。

I'm not sure why your code works at all. 我不确定为什么您的代码可以正常工作。 Your code is missing a ) and ); 您的代码缺少a )); . Also I haven't tested with such an old version of jQuery. 另外,我还没有使用过旧版本的jQuery进行过测试。

See: 看到:

$(document).ready(function() {
      $('#footer a').click(function () {
          $("body").animate({scrollTop:0},1000);
      });
});

http://jsfiddle.net/4SV75/ http://jsfiddle.net/4SV75/

The problem is that your javascript is missing some closing parenthesis ) . 问题在于您的javascript缺少一些右括号( ) Here is the fixed version I used: 这是我使用的固定版本:

  $(document).ready(function(){
      $('#footer a').click(function (event) {
          $('body,html').animate({scrollTop:0},1000);
          event.preventDefault();
      });
  });

jsfiddle: http://jsfiddle.net/tAbqW/ jsfiddle: http : //jsfiddle.net/tAbqW/

The reason it is sending you to the top is most likely you used href='#' , which will send you to the top even with no javascript. 将您带到顶部的原因很可能是您使用了href='#' ,即使没有JavaScript也可以将您带到顶部。

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

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