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


当前回答

document.getElementById(“elem”)scrollIntoView();

其他回答

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

如果你不需要更改动画,那么你就不需要使用任何特殊的插件——我只需要使用原生JavaScript window.scrollTo()方法——传入0,0将立即将页面滚动到左上角。

window.scrollTo(xCoord, yCoord);

参数

xCoord是沿水平轴的像素。yCoord是沿垂直轴的像素。

以上答案在SharePoint 2016中都不起作用。

必须这样做:https://sharepoint.stackexchange.com/questions/195870/

var w = document.getElementById("s4-workspace");
w.scrollTop = 0;
function scrolltop() {

    var offset = 220;
    var duration = 500;

    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('#back-to-top').fadeIn(duration);
        } else {
            jQuery('#back-to-top').fadeOut(duration);
        }
    });

    jQuery('#back-to-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    });
}

最短的

location='#'

这种解决方案是对pollinrata答案的改进,并且有一些缺点:没有平滑的滚动和更改页面位置,但最短