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

如何使用JavaScript/jQuery滚动到页面顶部?,javascript,jquery,html,scroll,Javascript,Jquery,Html,Scroll,有没有办法用JavaScript/jQuery控制浏览器滚动 当我将页面向下滚动到一半,然后触发重新加载时,我希望页面能够压缩到顶部,但它会尝试查找最后一个滚动位置。所以我这样做了: $('document').ready(function() { $(window).scrollTop(0); }); 但是没有运气 编辑: 所以当我在页面加载后给他们打电话时,你的两个答案都起作用了,谢谢。但是,如果我只是在页面上进行刷新,看起来浏览器会在.ready事件之后计算并滚动到原来的滚动位置(

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

当我将页面向下滚动到一半,然后触发重新加载时,我希望页面能够压缩到顶部,但它会尝试查找最后一个滚动位置。所以我这样做了:

$('document').ready(function() {
   $(window).scrollTop(0);
});
但是没有运气

编辑

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


因此,接下来的问题是,有没有办法防止浏览器滚动到其过去的位置,或者在它完成操作后重新滚动到顶部?

您几乎了解了它-您需要在
主体
上设置
滚动顶部
,而不是
窗口

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

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

$(function() {
   $('<a name="top"/>').insertBefore($('body').children().eq(0));
   window.location.hash = 'top';
});
let ele = document.getElementsByClassName('md-sidenav-content');
    let eleArray = <Element[]>Array.prototype.slice.call(ele);
    eleArray.map( val => {
        val.scrollTop = document.documentElement.scrollTop = 0;
    });
$(函数(){
$('').insertBefore($('body').children().eq(0));
window.location.hash='top';
});

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

document.body.scrollTop = document.documentElement.scrollTop = 0;
function gototop() {
    if (window.scrollY>0) {
        window.scrollTo(0,window.scrollY-20)
        setTimeout("gototop()",10)
    }
}

要回答您的问题,您可以注册
onscroll
处理程序,如下所示:

document.documentElement.onscroll = document.body.onscroll = function() {
    this.scrollTop = 0;
    this.onscroll = null;
}
这将使首次尝试滚动(很可能是浏览器自动完成的滚动)有效取消。

这对我来说很有用:

window.onload = function() {
    // short timeout
    setTimeout(function() {
        $(document.body).scrollTop(0);
    }, 15);
};
$(window).unload(function() {
    $('body').scrollTop(0);
});
onload
中使用一个短
setTimeout
,让浏览器有机会进行滚动

有没有一种方法可以阻止浏览器 滚动到其过去的位置,或 完成后重新滚动到顶部 事情

以下jquery解决方案适合我:

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

Seeint散列应该完成这项工作。如果有标题,可以使用

window.location.href = "#headerid";
否则,单靠#就行了

window.location.href = "#";
当它被写入url时,如果您刷新,它将保持不变


事实上,您不需要JavaScript,如果您想在onclick事件上执行此操作,您应该在元素周围放置一个链接,并给它#as href。

为什么不在html文件的最开始使用一些引用元素,如

<div id="top"></div>
如果此函数启动后浏览器滚动,则只需执行以下操作

$(document).ready(function(){

    top.location.href = '#top';

});
$(window).load(function(){

    top.location.href = '#top';

});

使用此

以下代码在Firefox、Chrome和中都可以使用,但我无法在InternetExplorer中测试。有人可以测试它,然后编辑我的答案或评论吗

$(document).scrollTop(0);

首先,将一个空白的锚定标记添加到您想去的地方

<a href="#topAnchor"></a> 
最后,将onload事件添加到body标记

<body onload="GoToTop()">

在我的情况下,身体不起作用:

$('body').scrollTop(0);
但HTML起了作用:

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

下面是一个纯JavaScript动画滚动版本,用于no-jQuery'ers: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>
向上滚动

跨浏览器滚动至顶部:

        if($('body').scrollTop()>0){
            $('body').scrollTop(0);         //Chrome,Safari
        }else{
            if($('html').scrollTop()>0){    //IE, FF
                $('html').scrollTop(0);
            }
        } 
跨浏览器滚动到id=div\u 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);
            }
        } 
var tototop=$('#totop');
totop.click(函数(){
$('html,body').stop(true,true).animate({scrollTop:0},1000);
返回false;
});
$(窗口)。滚动(函数(){
如果($(this).scrollTop()>100){
totop.fadeIn();
}否则{
totop.fadeOut();
}
});
如果您处于怪癖模式(感谢@Niet the Dark Absol):

如果您处于严格模式:

document.documentElement.scrollTop = 0;
这里不需要jQuery。

这是可行的:

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

可以与jQuery一起使用

jQuery(window).load(function(){

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

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

document.body.scrollTop = document.documentElement.scrollTop = 0;
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
语句检查我们是否仍然需要滚动。

一个通用版本,适用于任何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();
}

更新

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

有两种方法可以使用
滚动API

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

窗口。滚动(选项)

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

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});
另一种方法是使用x和y坐标

窗口。滚动(x坐标,y坐标)

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

y坐标-是沿文档纵轴的像素,您希望显示在左上角


旧答案不使用

这是我们的香草
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);
document.querySelector(“顶部”).addEventListener(“单击”,函数)(){
var toTopInterval=setInterval(函数(){
var supportedScrollTop=document.body.scrollTop>0?document.body:document.documentElement;
如果(supportedScrollTop.scrollTop>0){
supportedScrollTop.scrollTop=supportedScrollTop.scrollTop-50;
}
如果(支持scrollTop.scrollTop<1){
净空间隔(totointerval);
}
}, 10);
},假);
HTML

<button id="to-top">To Top</button>
到顶部
干杯

没有动画,
let ele = document.getElementsByClassName('md-sidenav-content');
    let eleArray = <Element[]>Array.prototype.slice.call(ele);
    eleArray.map( val => {
        val.scrollTop = document.documentElement.scrollTop = 0;
    });
 <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>
 setTimeout(function () {
        window.scroll({
                        top: 0,
                        left: 0,
                        behavior: 'smooth'
                    });

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

}, 15);
// 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);
$(function() {
  // put the code here
});
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.
} 
setTimeout(() => {
    window.scrollTo(0, 0);
}, 0);
document.body.scrollIntoView({behavior: "smooth"});