如何使用JavaScript/jQuery滚动到页面顶部?

Yar*_*rin 146 html javascript jquery scroll

有没有办法用JavaScript/jQuery控制浏览器滚动?

当我将页面向下滚动一半,然后触发重新加载时,我希望页面打包到顶部,而是尝试查找最后一个滚动位置.所以我这样做了:

$('document').ready(function() {
   $(window).scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)

但没有运气.

编辑:

因此,当我在页面加载后调用它们时,你的答案都有效 - 谢谢.但是,如果我只是在页面上刷新,看起来浏览器计算并滚​​动到.ready事件后的旧滚动位置(我也测试了body onload()函数).

那么跟进是,有没有办法防止浏览器滚动到其过去的位置,或者重新滚动到顶部它做它的事情后?

Nie*_*sol 299

跨浏览器,纯JavaScript解决方案:

document.body.scrollTop = document.documentElement.scrollTop = 0;
Run Code Online (Sandbox Code Playgroud)

  • 既然你正在使用jQuery,你可以试试这个:`$(window).one("scroll",function(){/*我在这里答案的代码*/}); (3认同)

Jac*_*kin 85

几乎得到它-你需要设置scrollTopbody,而不是window:

$(function() {
   $('body').scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)

编辑:

也许你可以在页面顶部添加一个空白锚点:

$(function() {
   $('<a name="top"/>').insertBefore($('body').children().eq(0));
   window.location.hash = 'top';
});
Run Code Online (Sandbox Code Playgroud)

  • 今天尝试了这个并且没有在FF16中工作.使用纯JS,在本页的较低位置,而不是:document.body.scrollTop = document.documentElement.scrollTop = 0; (2认同)
  • 上面的代码可以在现代浏览器中正常工作,如FF,Chrome但它在IE8及以下版本中无法正常工作,尝试添加"html","body",因为现代浏览器将根据正文滚动但IE8及以下版本仅会滚动**'html','body'** (2认同)

Ray*_*ess 53

哇,我问这个问题晚了 9 年。干得好:

将此代码添加到您的 onload.xml 文件中。

// This prevents the page from scrolling down to where it was previously.
if ('scrollRestoration' in history) {
    history.scrollRestoration = 'manual';
}
// This is needed if the user scrolls down during page load and you want to make sure the page is scrolled to the top once it's fully loaded. This has Cross-browser support.
window.scrollTo(0,0);
Run Code Online (Sandbox Code Playgroud)

要在窗口加载时运行它,只需像这样将它包装起来(假设您引用了JQuery

$(function() {
  // put the code here
});
Run Code Online (Sandbox Code Playgroud)

history.scrollRestoration 浏览器支持:

Chrome:支持(自 46 起)

Firefox:支持(自 46 起)

边缘:支持(自 79 起)

IE:不支持

Opera:支持(自 33 起)

Safari:支持

对于IE,如果您想在它自动向下滚动后重新滚动到顶部,那么这对我有用:

var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
if(isIE11) {
    setTimeout(function(){ window.scrollTo(0, 0); }, 300);  // adjust time according to your page. The better solution would be to possibly tie into some event and trigger once the autoscrolling goes to the top.
} 
Run Code Online (Sandbox Code Playgroud)

  • 投票是因为帮助别人永远不会太晚;即使是9年后。谢谢你! (3认同)

Mat*_*att 16

有没有办法防止浏览器滚动到其过去的位置,或重新滚动到顶部它做它的事情后?

以下jquery解决方案适合我:

$(window).unload(function() {
    $('body').scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)


ulf*_*ryk 15

这是一个纯JavaScript动画滚动版本,适用于没有jQuery的人:D

var stepTime = 20;
var docBody = document.body;
var focElem = document.documentElement;

var scrollAnimationStep = function (initPos, stepAmount) {
    var newPos = initPos - stepAmount > 0 ? initPos - stepAmount : 0;

    docBody.scrollTop = focElem.scrollTop = newPos;

    newPos && setTimeout(function () {
        scrollAnimationStep(newPos, stepAmount);
    }, stepTime);
}

var scrollTopAnimated = function (speed) {
    var topOffset = docBody.scrollTop || focElem.scrollTop;
    var stepAmount = topOffset;

    speed && (stepAmount = (topOffset * stepTime)/speed);

    scrollAnimationStep(topOffset, stepAmount);
};
Run Code Online (Sandbox Code Playgroud)

然后:

<button onclick="scrollTopAnimated(1000)">Scroll Top</button>
Run Code Online (Sandbox Code Playgroud)


Nit*_*hav 15

2021 年的现代解决方案

document.body.scrollIntoView({behavior: "smooth"});
Run Code Online (Sandbox Code Playgroud)

适用于包括 IE 在内的所有浏览器(较旧的浏览器不支持平滑滚动)。

在此输入图像描述


Jo *_* E. 11

UPDATE

使用滚动效果转到页面顶部在javascript中更容易实现:

https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});
Run Code Online (Sandbox Code Playgroud)

警告

我们在最近的项目中一直在使用它,但我刚刚检查了mozilla文档,同时更新了我的答案,我相信它已经更新了.现在,该方法是window.scroll(x-coord, y-coord)并且没有提及或显示使用object您可以设置behaviorto 的参数的示例smooth.我只是尝试了代码,它仍然适用于chrome和firefox,对象参数仍然在规范中.

因此请谨慎使用,否则您可以使用此Polyfill.除了滚动到顶部,这也填充工具处理其他方法:window.scrollBy,element.scrollIntoView,等.


老答复

这是我们的香草javascript实施.它具有简单的缓动效果,因此用户在单击" 顶部"按钮后不会感到震惊.

它非常小,在缩小时变得更小.寻找替代jquery方法但想要相同结果的开发人员可以试试这个.

JS

document.querySelector("#to-top").addEventListener("click", function(){

    var toTopInterval = setInterval(function(){

        var supportedScrollTop = document.body.scrollTop > 0 ? document.body : document.documentElement;

        if (supportedScrollTop.scrollTop > 0) {
            supportedScrollTop.scrollTop = supportedScrollTop.scrollTop - 50;
        }

        if (supportedScrollTop.scrollTop < 1) {
            clearInterval(toTopInterval);
        }

    }, 10);

},false);
Run Code Online (Sandbox Code Playgroud)

HTML

<button id="to-top">To Top</button>
Run Code Online (Sandbox Code Playgroud)

干杯!


use*_*716 8

这对我有用:

window.onload = function() {
    // short timeout
    setTimeout(function() {
        $(document.body).scrollTop(0);
    }, 15);
};
Run Code Online (Sandbox Code Playgroud)

setTimeout在内部使用一个简短的内容onload,让浏览器有机会进行滚动.


小智 8

你可以使用jQuery

jQuery(window).load(function(){

    jQuery("html,body").animate({scrollTop: 100}, 1000);

});
Run Code Online (Sandbox Code Playgroud)


big*_*ind 6

以下代码适用于 Firefox、Chrome 和Safari,但我无法在 Internet Explorer 中测试它。有人可以测试它,然后编辑我的答案或对其发表评论吗?

$(document).scrollTop(0);
Run Code Online (Sandbox Code Playgroud)


小智 6

使用以下功能

window.scrollTo(xpos, ypos)
Run Code Online (Sandbox Code Playgroud)

这里xpos是必需的.要沿x轴(水平)滚动到的坐标(以像素为单位)

ypos也是必需的.要沿y轴(垂直)滚动到的坐标,以像素为单位


Eki*_*taç 5

$(function() {
    // the element inside of which we want to scroll
        var $elem = $('#content');

        // show the buttons
    $('#nav_up').fadeIn('slow');
    $('#nav_down').fadeIn('slow');  

        // whenever we scroll fade out both buttons
    $(window).bind('scrollstart', function(){
        $('#nav_up,#nav_down').stop().animate({'opacity':'0.2'});
    });
        // ... and whenever we stop scrolling fade in both buttons
    $(window).bind('scrollstop', function(){
        $('#nav_up,#nav_down').stop().animate({'opacity':'1'});
    });

        // clicking the "down" button will make the page scroll to the $elem's height
    $('#nav_down').click(
        function (e) {
            $('html, body').animate({scrollTop: $elem.height()}, 800);
        }
    );
        // clicking the "up" button will make the page scroll to the top of the page
    $('#nav_up').click(
        function (e) {
            $('html, body').animate({scrollTop: '0px'}, 800);
        }
    );
 });
Run Code Online (Sandbox Code Playgroud)

用这个


Toa*_*gma 5

我的纯(动画)Javascript 解决方案:

function gototop() {
    if (window.scrollY>0) {
        window.scrollTo(0,window.scrollY-20)
        setTimeout("gototop()",10)
    }
}
Run Code Online (Sandbox Code Playgroud)

解释:

window.scrollY是由浏览器维护的变量,表示窗口滚动到顶部的像素数量。

window.scrollTo(x,y)是一个函数,可将窗口在 x 轴和 y 轴上滚动特定数量的像素。

因此,window.scrollTo(0,window.scrollY-20)将页面向顶部移动 20 个像素。

10 毫秒后再次调用setTimeout该函数,以便我们可以将其再移动 20 像素(动画),并且该if语句检查是否仍然需要滚动。