如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
平滑动画的更好解决方案:
// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });
参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example
其他回答
<script>
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
</script>
html格式
<a href="#top">go top</a>
如果您确实想要平滑滚动,请尝试以下操作:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。
如果您想设置滚动动作的动画,则不需要javascript、event!
CSS:
html {
scroll-behavior: smooth;
}
HTML格式:
<html>
<body>
<a id="top"></a>
<!-- your document -->
<a href="#top">Jump to top of page</a>
</body>
</html>
如果您不希望平滑滚动,您可以在启动平滑滚动动画时立即欺骗并停止它……如下所示:
$(document).ready(function() {
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "1");
$('html, body').stop(true, true);
//Anything else you want to do in the same action goes here
return false;
});
});
我不知道它是否被推荐/允许,但它有效:)
你什么时候用这个?我不确定,但也许当您想使用Jquery一键制作一件事情的动画,而不使用动画制作另一件事情时?即打开页面顶部的管理登录面板中的幻灯片,然后立即跳到顶部查看。
您可以使用javascript的内置函数scrollTo:
函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?