如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。


当前回答

$(“.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>

其他回答

如果您确实想要平滑滚动,请尝试以下操作:

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。

$(“.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>

使用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>

请检查以下代码,这肯定会有帮助。:)

document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.

你不需要JQuery。只需调用脚本

window.location = '#'

单击“转到顶部”按钮

示例演示:

输出.jsbin.com/fakumo#

PS:当你使用像angularjs这样的现代库时,不要使用这种方法。这可能会破坏URL散列。