如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
<script>
$(function(){
var scroll_pos=(0);
$('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>
编辑:
$('html, body').animate({scrollTop:(scroll_pos)}, 2000);
另一种上下边距滚动方式:
window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });
其他回答
你可以尝试在这个Fiddle中使用JShttp://jsfiddle.net/5bNmH/1/
在页脚中添加“转到顶部”按钮:
<footer>
<hr />
<p>Just some basic footer text.</p>
<!-- Go to top Button -->
<a href="#" class="go-top">Go Top</a>
</footer>
真的很奇怪:这个问题已经活跃了五年了,但仍然没有一个普通的JavaScript答案来激活滚动……所以,现在就开始吧:
var scrollToTop = window.setInterval(function() {
var pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 16); // how fast to scroll (this equals roughly 60 fps)
如果愿意,可以将其包装在函数中,并通过onclick属性调用它。检查这个jsfiddle
注意:这是一个非常基本的解决方案,可能不是最有效的解决方案。这里可以找到一个非常详细的示例:https://github.com/cferdinandi/smooth-scroll
只需尝试,不需要其他插件/框架
document.getElementById(“jarscoolbtn”).addEventListener(“单击”,jarsrollfunction);函数jarrollfunction(){var body=document.body;//对于Safarivar html=document.documentElement;//Chrome、Firefox、IE和Operabody.scrollTop=0;html.scrollTop=0;}<button id=“jarscoolbtn”>滚动内容</button>html,正文{滚动行为:平滑;}
document.getElementById(“elem”)scrollIntoView();
许多用户建议同时选择html和body标签以实现跨浏览器兼容性,如下所示:
$('html, body').animate({ scrollTop: 0 }, callback);
如果你指望回调只运行一次,这可能会让你绊倒。它实际上会运行两次,因为您选择了两个元素。
如果这对你来说是个问题,你可以这样做:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
$('body').animate({ scrollTop: 0 }, callback);
}
这在Chrome$('html')中有效的原因。scrollTop()返回0,但在其他浏览器(如Firefox)中无效。
如果滚动条已经位于顶部,您不想等待动画完成,请尝试以下操作:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, callback);
return;
}
callback();
}
推荐文章
- 错误:'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授权头
- 为什么我的球(物体)没有缩小/消失?