如何使用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
其他回答
请检查以下代码,这肯定会有帮助。:)
document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
只需使用此脚本滚动到顶部直接。
<script>
$(document).ready(function(){
$("button").click(function(){
($('body').scrollTop(0));
});
});
</script>
使用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>
如果您想滚动到具有ID的任何元素,请尝试以下操作:
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 700, 'swing', function () {
window.location.hash = target;
});
});``
如果您不希望平滑滚动,您可以在启动平滑滚动动画时立即欺骗并停止它……如下所示:
$(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一键制作一件事情的动画,而不使用动画制作另一件事情时?即打开页面顶部的管理登录面板中的幻灯片,然后立即跳到顶部查看。
推荐文章
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 使用jQuery滚动到一个div
- 在JS/jQuery中触发按键/按键/按键事件?