我正在写一个模态弹出窗口,我需要浏览器跳转到屏幕的顶部,当打开模态按钮被按下。是否有一种方法可以使用jQuery将浏览器滚动到顶部?
你可以像这样设置scrollTop:
$('html,body').scrollTop(0);
或者如果你想要一个小动画而不是一个快照到顶部:
$('html, body').animate({ scrollTop: 0 }, 'fast');
如果你正在使用jQuery UI对话框,你可以只是样式的模式出现在窗口固定的位置,所以它不会弹出出视图,否定需要滚动。否则,
var scrollTop = function() {
window.scrollTo(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>
我知道这是旧的,但对于那些在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);但是选项的兼容性较差。(参考)。
推荐文章
- 转换php数组到Javascript
- 如何跳转到浏览器页面的顶部
- CSS: 100%的宽度或高度,同时保持纵横比?
- 确定$。Ajax错误是一个超时
- 在电子邮件消息中是否支持JavaScript ?
- 如何在JavaScript中指定Math.log()的基?
- 多重左赋值JavaScript
- 使用jQuery创建、读取和删除cookie
- 如何在单个测试基础上更改模拟实现?
- VueJS有条件地为元素添加属性
- Uncaught TypeError:(中间值)(…)不是一个函数
- 如何设置URL查询参数在Vue与Vue路由器
- 无法读取属性“addEventListener”为空
- 如何防止moment.js从webpack加载地区?
- getMonth在javascript中给出前一个月