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


当前回答

// 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>

其他回答

你可以像这样设置scrollTop:

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

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

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

Vanilla Javascript解决方案

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

如果你想平滑滚动

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

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

scroll(0,0)

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

// 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>

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

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