简体   繁体   English

使用javascript滚动到元素时添加平滑效果

[英]add smooth effect when scrolling to element with javascript

I have coded the following function that whenever a certain button is clicked, view is scrolled to a specific element that matches the 'href' attribute.我编写了以下函数,每当单击某个按钮时,视图就会滚动到与“href”属性匹配的特定元素。

I would like to add a smooth effect to the scrolling.我想为滚动添加平滑效果。 Right now it simply goes to the element.现在它只是去元素。

<script src="/javascripts/application.js" type="text/javascript" charset="utf-8" async defer>
    $(function() {

        $(".button").on("click", function( e ) {

            e.preventDefault();

            $("body, html").animate({ 
                scrollTop: $( $(this).attr('href') ).offset().top 
            }, 600);

        });

    });
</script>

Any help is appreciated.任何帮助表示赞赏。 Thanks.谢谢。

Your code is perfect just edit your code like this (see below).您的代码是完美的,只需像这样编辑您的代码(见下文)。

You have written in on script tag which is loading external script file as well as inline script.您已经写入了加载外部脚本文件和内联脚本的脚本标签。

<script src="/javascripts/application.js" type="text/javascript" charset="utf-8" async defer> </script>
<script>
  $(function() { 
    $(".button").on("click", function( e ) { 
      e.preventDefault(); 
      $("body, html").animate({ scrollTop: $( $(this).attr('href') ).offset().top}, 600); 
    }); 
  });
</script>

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

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