ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

$('document').ready(function() {
   $(window).scrollTop(0);
});

但没有运气。

编辑:

因此,当我在页面加载后给他们打电话时,您的两个答案都有效-谢谢。但是,如果我只是在页面上进行刷新,看起来浏览器会在 .ready 事件之后计算并滚动到它的旧滚动位置(我也测试了 body onload() 函数)。

所以接下来是,有没有办法阻止浏览器滚动到它过去的位置,或者在它完成它的事情之后重新滚动到顶部?

当您从 $(window).load() 执行此操作时会发生什么?
@MPD-好主意! ...但只是尝试过,之后滚动调整仍然发生。不过感谢您的提示,它实际上有助于解决我的另一个问题:stackoverflow.com/questions/4210829/…。如果你想回答这个问题,我会给你一些 ups。
@Yarin 抱歉,您为此等了 9 年。您需要在尝试滚动之前设置 history.scrollRestoration。看我的回答。

P
Peter Mortensen

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

document.body.scrollTop = document.documentElement.scrollTop = 0;

由于您使用的是 jQuery,您可以试试这个:$(window).one("scroll",function() { /* the code from my answer here */ });
要在我的 IE/Chrome/FF 跨浏览器上进行这项工作,我必须结合 Niet Dark Absol 答案和 user113716 答案(使用超时)。
无法在使用 FF 45.1.0 的 CentOS 6.7 上工作。我把它包装在一个文件中。准备好只是为了确定。
只是想指出,从我的测试(包括现代/2018 版本的 chrome)中,该解决方案更可靠地工作
这不会“阻止浏览器滚动到其过去的位置”。看我的回答。
J
Jacob Relkin

几乎明白了 - 您需要在 body 上设置 scrollTop,而不是在 window 上:

$(function() {
   $('body').scrollTop(0);
});

编辑:

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

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

今天试过了,在FF16中没有用。使用本页下方的纯 JS,而不是:document.body.scrollTop = document.documentElement.scrollTop = 0;
上面的代码在现代浏览器(如 FF、Chrome)中可以正常工作,但在 IE8 及以下版本中无法正常运行html','正文'
E
Eugene

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

将此代码添加到您的 onload。

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

要在窗口加载时运行它,只需将其包裹起来(假设您已引用 JQuery

$(function() {
  // put the code here
});

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.
} 

感谢@RayLoveless - 不幸的是,MS 浏览器不支持此功能(因为当然)。请参阅 caniuse.com/#feat=mdn-api_history_scrollrestorationdeveloper.mozilla.org/de/docs/Web/API/…
@Yarin,好点。我更新了我的帖子。这是否回答你的问题?
@RayLoveless 现在 Edge 支持它。
@NikolaStojaković,谢谢,我已相应更新。
支持,因为帮助别人永远不会太晚;即使是9年后。谢谢!
J
Jo E.

更新

现在在 javascript 中使用滚动效果进入页面顶部更容易:

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

有 2 种使用 scroll API 的方法。

这是我推荐的方法。使用 option 对象:

window.scroll(options)

这是一个更好的选择,因为您可以定义一个应用内置缓动动画的 behavior 道具。

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});

另一种方法是使用 x 和 y 坐标。

window.scroll(x-coord, y-coord)

x-coord - 是您希望在左上角显示的文档水平轴上的像素。

坐标 - 是您希望在左上角显示的文档垂直轴上的像素。

旧答案不要使用

这是我们的普通 javascript 实现。它有一个简单的缓动效果,这样用户在点击To Top按钮后不会感到震惊。

它非常小,缩小后会变得更小。正在寻找 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);

HTML

<button id="to-top">To Top</button>

干杯!


M
Matt

有没有办法阻止浏览器滚动到它过去的位置,或者在它完成它之后重新滚动到顶部?

以下 jquery 解决方案适用于我:

$(window).unload(function() {
    $('body').scrollTop(0);
});

是的,在刷新之前滚动到顶部
不完全跨浏览器,但仍然适用于大多数人。当与其他一些答案结合使用时,这是一个很好的补充
P
Peter Mortensen

这是一个纯 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);
};

接着:

<button onclick="scrollTopAnimated(1000)">Scroll Top</button>

凉爽的。不过,我更喜欢 requestAnimationStep 而不是 setTimeout。它也没有回答 OP 的问题。
在 Angular 中实现了这一点。奇迹般有效。谢谢
u
user113716

这对我有用:

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

onload 中使用一个短的 setTimeout 让浏览器有机会进行滚动。


要在我的 IE/Chrome/FF 跨浏览器上进行这项工作,我必须结合 Niet Dark Absol 答案和 user113716 答案(使用超时)。
@Panini:您的建议适用于 Chrome/FF,但不适用于 IE11。
K
Kromster

您可以使用 jQuery

jQuery(window).load(function(){

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

});

这基本上是我最终发现使用 FF 45.1.0 在 CentOS 6.7 上工作的内容。我略有不同的版本(包含在窗口加载函数中)是: $("html, body").animate({ scrollTop: 0 }, 1);
A
Ahad

使用以下功能

window.scrollTo(xpos, ypos)

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

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


A
AdamMcquiff

A modern solution in 2021

document.body.scrollIntoView({behavior: "smooth"});

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

https://i.stack.imgur.com/K5xwc.png


这正是我所需要的。谢谢
E
Ekin Ertaç
$(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);
        }
    );
 });

用这个


好的!动画效果很好!
P
Peter Mortensen

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

$(document).scrollTop(0);

a
arik

为什么不在 html 文件的开头使用一些参考元素,比如

<div id="top"></div>

然后,当页面加载时,只需执行

$(document).ready(function(){

    top.location.href = '#top';

});

如果此函数触发后浏览器滚动,您只需执行

$(window).load(function(){

    top.location.href = '#top';

});

这对我有用,但它在 url 中添加了#top,你能告诉我如何避免这种情况,但同时,不影响功能
T
Toastrackenigma

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

function gototop() {
    if (window.scrollY>0) {
        window.scrollTo(0,window.scrollY-20)
        setTimeout("gototop()",10)
    }
}

解释:

window.scrollY 是一个由浏览器维护的变量,它表示窗口从顶部开始滚动的像素数量。

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

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

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


B
Binod Kalathil

跨浏览器滚动到顶部:

        if($('body').scrollTop()>0){
            $('body').scrollTop(0);         //Chrome,Safari
        }else{
            if($('html').scrollTop()>0){    //IE, FF
                $('html').scrollTop(0);
            }
        } 

跨浏览器滚动到 id = div_id 的元素:

        if($('body').scrollTop()>$('#div_id').offset().top){
            $('body').scrollTop($('#div_id').offset().top);         //Chrome,Safari
        }else{
            if($('html').scrollTop()>$('#div_id').offset().top){    //IE, FF
                $('html').scrollTop($('#div_id').offset().top);
            }
        } 

佚名

如果您处于怪癖模式(感谢@Niet the Dark Absol):

document.body.scrollTop = document.documentElement.scrollTop = 0;

如果您处于严格模式:

document.documentElement.scrollTop = 0;

这里不需要 jQuery。


G
Giacomo1968

在我的情况下,身体没有工作:

$('body').scrollTop(0);

但 HTML 工作:

$('html').scrollTop(0);

将两个 'html','body' 添加为现代浏览器 FF,Chrome 将根据 body 滚动,但 IE8 及以下版本将仅使用 'html','body' 滚动
N
Niet the Dark Absol

要回答您编辑的问题,您可以像这样注册 onscroll 处理程序:

document.documentElement.onscroll = document.body.onscroll = function() {
    this.scrollTop = 0;
    this.onscroll = null;
}

这将使第一次滚动尝试(可能是浏览器自动完成)将被有效取消。


不错的解决方案-我会试一试
P
Peter Mortensen

这是有效的:

jQuery(document).ready(function() {
     jQuery("html").animate({ scrollTop: 0 }, "fast");
});

s
shailesh gavathe

这两者的结合帮助了我。因为我有一个不滚动的sidenav,所以其他答案都没有帮助我。

 setTimeout(function () {
        window.scroll({
                        top: 0,
                        left: 0,
                        behavior: 'smooth'
                    });

    document.body.scrollTop = document.documentElement.scrollTop = 0;

}, 15);

J
John Koerner
var totop = $('#totop');
totop.click(function(){
 $('html, body').stop(true,true).animate({scrollTop:0}, 1000);
 return false;
});

$(window).scroll(function(){
 if ($(this).scrollTop() > 100){ 
  totop.fadeIn();
 }else{
  totop.fadeOut();
 }
});

<img id="totop" src="img/arrow_up.png" title="Click to go Up" style="display:none;position:fixed;bottom:10px;right:10px;cursor:pointer;cursor:hand;"/>

m
maxbellec

没有动画,只有 scroll(0, 0) (vanilla JS)


P
Post Impatica

如果有人在 sidenav 中使用角度和材料设计。这会将您带到页面顶部:

let ele = document.getElementsByClassName('md-sidenav-content');
    let eleArray = <Element[]>Array.prototype.slice.call(ele);
    eleArray.map( val => {
        val.scrollTop = document.documentElement.scrollTop = 0;
    });

x
xavierm02

Seeint 哈希应该可以完成这项工作。如果你有一个标题,你可以使用

window.location.href = "#headerid";

否则,单独的 # 将起作用

window.location.href = "#";

当它被写入 url 时,如果你刷新它就会留下来。

事实上,如果您想在 onclick 事件上执行此操作,则不需要 JavaScript,您只需在元素周围放置一个链接并将其 # 作为 href。


顺便说一句,window.location 不是树的一部分,所以现在可以用来等待 onload。
S
Satii

首先在你想去的地方添加一个空白的锚标签

<a href="#topAnchor"></a> 

现在在标题部分添加一个函数

 function GoToTop() {
            var urllocation = location.href;
            if (urllocation.indexOf("#topAnchor") > -1) {
                window.location.hash = "topAnchor";
            } else {
                return false;
            }
        }

最后在body标签中添加一个onload事件

<body onload="GoToTop()">

j
jamesmfriedman

适用于任何 X 和 Y 值的通用版本,与 window.scrollTo api 相同,只是添加了 scrollDuration。

*与 window.scrollTo 浏览器 api 匹配的通用版本**

function smoothScrollTo(x, y, scrollDuration) {
    x = Math.abs(x || 0);
    y = Math.abs(y || 0);
    scrollDuration = scrollDuration || 1500;

    var currentScrollY = window.scrollY,
        currentScrollX = window.scrollX,
        dirY = y > currentScrollY ? 1 : -1,
        dirX = x > currentScrollX ? 1 : -1,
        tick = 16.6667, // 1000 / 60
        scrollStep = Math.PI / ( scrollDuration / tick ),
        cosParameterY = currentScrollY / 2,
        cosParameterX = currentScrollX / 2,
        scrollCount = 0,
        scrollMargin;

    function step() {        
        scrollCount = scrollCount + 1;  

        if ( window.scrollX !== x ) {
            scrollMargin = cosParameterX + dirX * cosParameterX * Math.cos( scrollCount * scrollStep );
            window.scrollTo( 0, ( currentScrollX - scrollMargin ) );
        } 

        if ( window.scrollY !== y ) {
            scrollMargin = cosParameterY + dirY * cosParameterY * Math.cos( scrollCount * scrollStep );
            window.scrollTo( 0, ( currentScrollY - scrollMargin ) );
        } 

        if (window.scrollX !== x || window.scrollY !== y) {
            requestAnimationFrame(step);
        }
    }

    step();
}

K
Kenrick Humber
 <script>
  sessionStorage.scrollDirection = 1;//create a session variable 
  var pageScroll = function() {
  window.scrollBy ({
   top: sessionStorage.scrollDirection,
   left: 0,
   behavior: 'smooth'
   });
   if($(window).scrollTop() + $(window).height() > $(document).height() - 1)
  {    
    sessionStorage.scrollDirection= Number(sessionStorage.scrollDirection )-300;
    setTimeout(pageScroll,50);//
   }
   else{
   sessionStorage.scrollDirection=Number(sessionStorage.scrollDirection )+1
   setTimeout(pageScroll,300); 
  }
};
pageScroll();
</script>

欢迎来到stackoverflow。除了您提供的代码之外,请尝试解释为什么以及如何解决此问题。
G
Greyson R.

我记得在其他地方看到过这个帖子(我找不到在哪里),但这真的很好用:

setTimeout(() => {
    window.scrollTo(0, 0);
}, 0);

这很奇怪,但它的工作方式是基于 JavaScript 堆栈队列的工作方式。完整的解释可在零延迟部分找到 here

基本思想是 setTimeout 的时间实际上并没有指定它要等待的设定时间,而是它要等待的最短时间。因此,当您告诉它等待 0 毫秒时,浏览器会运行所有其他排队的进程(例如将窗口滚动到您上次所在的位置),然后执行回调。