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


当前回答

当顶部滚动条顶部小于限制底部,且底部到顶部滚动条标题为粘滞时。下面参见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/

其他回答

平滑动画的更好解决方案:

// 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

<script>

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

html格式

<a href="#top">go top</a>

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

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

使用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答案来激活滚动……所以,现在就开始吧:

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