我正在写一个模态弹出窗口,我需要浏览器跳转到屏幕的顶部,当打开模态按钮被按下。是否有一种方法可以使用jQuery将浏览器滚动到顶部?
当前回答
你可以这样做没有javascript和简单地使用锚标签?然后它将被那些免费的js访问。
虽然你正在使用情态动词,我假设你不关心js自由。;)
其他回答
你可以像这样设置scrollTop:
$('html,body').scrollTop(0);
或者如果你想要一个小动画而不是一个快照到顶部:
$('html, body').animate({ scrollTop: 0 }, 'fast');
你正在使用jQuery UI对话框,你可以只是样式的模式出现与窗口中的位置固定,所以它不会弹出出视图,否定需要滚动。其他
我知道这是旧的,但对于那些在Edge有问题的人:
普通JS: window.scrollTop=0;
不幸的是,scroll()和scrollTo()会在Edge中抛出错误。
// 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>
如果没有动画,你可以使用纯JS:
scroll(0,0)
用动画,检查尼克的答案。
推荐文章
- src和dist文件夹的作用是什么?
- 防止滚动条增加到Chrome页面的宽度
- 使用图像而不是单选按钮
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- Twitter Bootstrap 3 Sticky Footer