如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
如果您想设置滚动动作的动画,则不需要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>
其他回答
$(“.solltop”).click(函数){$(“html,body”).animate({scrollTop:0},“slow”);return false;});.节{高度:400px;}.第1节{背景色:#333;}.第2节{背景色:红色;}.第3节{背景色:黄色;}.第4节{背景色:绿色;}.滚动条{位置:固定;右:10px;底部:10px;颜色:#fff;}<html><head><title>滚动顶部演示</title><script src=“https://code.jquery.com/jquery-3.3.1.js“></script></head><body><div class=“content wrapper”><div class=“section section1”></div><div class=“section section2”></div><div class=“section section3”></div><div class=“section section4”></div>滚动顶部</a></div></body></html>
许多用户建议同时选择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();
}
你可以尝试在这个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>
请检查以下代码,这肯定会有帮助。:)
document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
使用AplineJS和TailwindCSS返回页首:
<button
x-cloak
x-data="{scroll : false}"
@scroll.window="document.documentElement.scrollTop > 20 ? scroll = true : scroll = false"
x-show="scroll" @click="window.scrollTo({top: 0, behavior: 'smooth'})"
type="button"
data-mdb-ripple="true"
data-mdb-ripple-color="light"
class="fixed inline-block p-3 text-xs font-medium leading-tight text-white uppercase transition duration-150 ease-in-out bg-blue-600 rounded-full shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg bottom-5 right-5"
id="btn-back-to-top"
x-transition.opacity
>
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z" clip-rule="evenodd" />
</svg>
</button>