我正在写一个模态弹出窗口,我需要浏览器跳转到屏幕的顶部,当打开模态按钮被按下。是否有一种方法可以使用jQuery将浏览器滚动到顶部?


你可以像这样设置scrollTop:

$('html,body').scrollTop(0);

或者如果你想要一个小动画而不是一个快照到顶部:

$('html, body').animate({ scrollTop: 0 }, 'fast');

如果没有动画,你可以使用纯JS:

scroll(0,0)

用动画,检查尼克的答案。


你可以这样做没有javascript和简单地使用锚标签?然后它将被那些免费的js访问。

虽然你正在使用情态动词,我假设你不关心js自由。;)


如果你正在使用jQuery UI对话框,你可以只是样式的模式出现在窗口固定的位置,所以它不会弹出出视图,否定需要滚动。否则,

var scrollTop = function() {
    window.scrollTo(0, 0);
};

应该能行。


你正在使用jQuery UI对话框,你可以只是样式的模式出现与窗口中的位置固定,所以它不会弹出出视图,否定需要滚动。其他


// When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { $('html, body').animate({scrollTop:0}, 'slow'); } body { font-family: Arial, Helvetica, sans-serif; font-size: 20px; } #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn:hover { background-color: #555; } <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> <div style="background-color:black;color:white;padding:30px">Scroll Down</div> <div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>


我知道这是旧的,但对于那些在Edge有问题的人:

普通JS: window.scrollTop=0;

不幸的是,scroll()和scrollTo()会在Edge中抛出错误。


Vanilla Javascript解决方案

theId.onclick = () => window.scrollTo({top: 0})

如果你想平滑滚动

theId.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' })

正如一些响应所暗示的那样,我必须使用window.scrollTo(0,0);而不是scrollTo(0,0);

window.scrollTo (0,0);工作与纯javascript在所有浏览器测试(无动画)。(MDN) (w3schools)。

 

来自MDN的例子:

没有选择:

window.scrollTo(0, 0);

使用选项:

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

下面是一个简单的例子,使用javascript内联html:

<button onclick="window.scrollTo(0, 0);">Click to scroll to top</button>

滚动流畅:

<button onclick="window.scrollTo({top: 0, left: 0, behavior: 'smooth'});">Smooth scroll</button>

注意: 在Chrome浏览器(例如89版)中,如果不首先启用平滑滚动,默认情况下似乎无法工作 chrome: / /标志/ #平滑滚动

 


window.scroll (0,0);类似于window.scrollTo(0,0);但是选项的兼容性较差。(参考)。