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


当前回答

旧的#top可以做到这一点

document.location.href = "#top";

适用于FF、IE和Chrome

其他回答

当顶部滚动条顶部小于限制底部,且底部到顶部滚动条标题为粘滞时。下面参见Fiddle示例。

var lastScroll = 0;

$(document).ready(function($) {

$(window).scroll(function(){

 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {

        $("header").removeClass("menu-sticky");

    } 
    if (scroll == 0) {
    $("header").removeClass("menu-sticky");

    }
    else if (scroll < lastScroll - 5) {


        $("header").addClass("menu-sticky");

    }
    lastScroll = scroll;
    },0);
    });
   });

https://jsfiddle.net/memdumusaib/d52xcLm3/

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

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

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

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

使用window.scrowlTo(0,0);速度非常快所以我尝试了Mark Ursino的例子,但在Chrome中什么都没有发生我找到了这个

$('.showPeriodMsgPopup').click(function(){
    //window.scrollTo(0, 0);
    $('html').animate({scrollTop:0}, 'slow');//IE, FF
    $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
    $('.popupPeriod').fadeIn(1000, function(){
        setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
    });
});

测试了所有3种浏览器,并正常工作我正在使用蓝图css这是当客户点击“立即预订”按钮并且没有选择租赁期时,慢慢移动到日历所在的顶部,并打开一个指向2个字段的对话框div,3秒后它会消失

平滑滚动,纯javascript:

(function smoothscroll(){
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
         window.requestAnimationFrame(smoothscroll);
         window.scrollTo (0,currentScroll - (currentScroll/5));
    }
})();