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


当前回答

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

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

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

其他回答

有趣的是,其中大多数根本不适合我,所以我使用了jQuery-ScrollTo.js:

wrapper.find(".jumpToTop").click(function() {
    $('#wrapper').ScrollTo({
        duration: 0,
        offsetTop: -1*$('#container').offset().top
    });
});

它奏效了$(document).sollTop()返回了0,而这个函数实际上起了作用。

TypeScript中的等效解决方案可能如下

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

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

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是一个例子。

为什么不使用JQuery内置函数scrollTop:

$('html, body').scrollTop(0);//For scrolling to top

$("body").scrollTop($("body")[0].scrollHeight);//For scrolling to bottom

简短而简单!