如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。


当前回答

如果您想滚动到具有ID的任何元素,请尝试以下操作:

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});``

其他回答

只需使用此脚本滚动到顶部直接。

<script>
$(document).ready(function(){
    $("button").click(function(){
        ($('body').scrollTop(0));
    });
});
</script>

请检查以下代码,这肯定会有帮助。:)

document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.

您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id。

或者,您可以使用任何数量的滚动插件,使其更加优雅。

http://plugins.jquery.com/project/ScrollTo是一个例子。

动机

这个简单的解决方案在本地工作,并实现了到任何位置的平滑滚动。

它避免了使用锚链接(带有#的链接),在我看来,如果你想链接到一个部分,这些链接是有用的,但在某些情况下不是很舒服,特别是当指向顶部时,这可能会导致两个不同的URL指向同一位置(http://www.example.org和http://www.example.org/#).

解决方案

在要滚动到的标记中添加一个id,例如第一个部分,它回答了这个问题,但id可以放在页面的任何位置。

<body>
  <section id="top">
    <!-- your content -->
  </section>
  <div id="another"><!-- more content --></div>

然后,作为一个按钮,您可以使用链接,只需使用如下代码编辑onclick属性即可。

<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>

其中document.getElementById的参数是单击后要滚动到的标记的id。

激活所有浏览器。祝你好运

var process;
        var delay = 50; //milisecond scroll top
        var scrollPixel = 20; //pixel U want to change after milisecond
        //Fix Undefine pageofset when using IE 8 below;
        function getPapeYOfSet() {
            var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
            return yOfSet;
        }



        function backToTop() {
            process = setInterval(function () {
                var yOfSet = getPapeYOfSet();
                if (yOfSet === 0) {
                    clearInterval(process);
                } else {
                    window.scrollBy(0, -scrollPixel);
                }
            }, delay);
        }