繁体   English   中英

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

[英]How to scroll to top of page with JavaScript/jQuery?

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

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

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

但没有运气。

编辑

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

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

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

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

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

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

编辑:

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

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

哇,我问这个问题晚了 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);

要在窗口加载时运行它,只需像这样将它包装起来(假设您引用了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.
} 

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

以下 jquery 解决方案对我有用:

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

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

更新

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

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

有两种使用scroll API

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

window.scroll(options)

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

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

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

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

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

y-coord - 是要在左上角显示的文档垂直轴上的像素。


旧答案请勿使用

这是我们的原生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);

HTML

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

干杯!

您可以与 jQuery 一起使用

jQuery(window).load(function(){

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

});

这对我有用:

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

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

使用以下功能

window.scrollTo(xpos, ypos)

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

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

$(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);
        }
    );
 });

用这个

我的纯(动画)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语句检查我们是否仍然需要滚动。

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

$(document).scrollTop(0);

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

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

但 HTML 有效:

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

跨浏览器滚动到顶部:

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

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

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

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

$(document).ready(function(){

    top.location.href = '#top';

});

如果浏览器此功能触发滚动,您只需执行

$(window).load(function(){

    top.location.href = '#top';

});

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

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

如果您处于严格模式:

document.documentElement.scrollTop = 0;

这里不需要 jQuery。

这是有效的:

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

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

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

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

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

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

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

}, 15);

2021 年的现代解决方案

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

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

在此处输入图片说明

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

没有动画,只是scroll(0, 0) (香草JS)

如果有人在 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;
    });

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

<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()">

适用于任何 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();
}
 <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(() => {
    window.scrollTo(0, 0);
}, 0);

这很奇怪,但它的工作方式是基于 JavaScript 堆栈队列的工作方式。 完整的解释发现这里的零延迟部分。

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

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

window.location.href = "#headerid";

否则, # 单独会起作用

window.location.href = "#";

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM