有没有办法用JavaScript / jQuery控制浏览器滚动?
当我将页面向下滚动一半,然后触发重新加载时,我希望页面打包到顶部,而是尝试查找最后一个滚动位置。所以我这样做了:
$('document').ready(function() {
$(window).scrollTop(0);
});
但没有运气。
修改:
因此,当我在页面加载后调用它们时,你的答案都有效 - 谢谢。但是,如果我只是在页面上刷新,看起来浏览器会计算并滚动到.ready
事件之后的旧滚动位置(我也测试了body onload()函数)。
所以后续工作是,有没有办法防止浏览器滚动到过去的位置,或者在它完成它之后重新滚动到顶部?
答案 0 :(得分:287)
跨浏览器的纯JavaScript解决方案:
document.body.scrollTop = document.documentElement.scrollTop = 0;
答案 1 :(得分:83)
您差不多得到它 - 您需要在scrollTop
上设置body
,而不是window
:
$(function() {
$('body').scrollTop(0);
});
编辑:
也许您可以在页面顶部添加空白锚点:
$(function() {
$('<a name="top"/>').insertBefore($('body').children().eq(0));
window.location.hash = 'top';
});
答案 2 :(得分:16)
有没有办法预防浏览器 滚动到过去的位置,或者 在它完成之后重新滚动到顶部 事?
以下jquery解决方案适用于我:
$(window).unload(function() {
$('body').scrollTop(0);
});
答案 3 :(得分:15)
这里是一个纯JavaScript动画滚动版本,适用于no-jQuery&#39;其他人: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>
答案 4 :(得分:9)
<强>更新强>
使用滚动效果在页面顶部使用javascript更加容易:
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
<强>注意强>
我们在最近的项目中一直在使用它,但我刚刚检查了mozilla文档,同时更新了我的答案,我相信它已经更新。目前该方法为window.scroll(x-coord, y-coord)
,并未提及或显示使用object
参数的示例,您可以将behavior
设置为smooth
。我只是尝试了代码,它仍然可以在chrome和firefox中使用,而object参数仍然在spec。
因此请谨慎使用,或者使用此Polyfill。除了滚动到顶部,此polyfill还处理其他方法:window.scrollBy
,element.scrollIntoView
等。
OLD ANSWER
这是我们的vanilla 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>
干杯!
答案 5 :(得分:8)
这对我有用:
window.onload = function() {
// short timeout
setTimeout(function() {
$(document.body).scrollTop(0);
}, 15);
};
在setTimeout
内使用短onload
,让浏览器有机会进行滚动。
答案 6 :(得分:8)
您可以使用jQuery
jQuery(window).load(function(){
jQuery("html,body").animate({scrollTop: 100}, 1000);
});
答案 7 :(得分:6)
使用以下功能
window.scrollTo(xpos, ypos)
这里xpos是必需的。要沿x轴(水平)滚动到的坐标,以像素为单位
ypos也是必需的。要沿y轴(垂直)滚动到的坐标,以像素为单位
答案 8 :(得分: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);
}
);
});
使用此
答案 9 :(得分:4)
以下代码适用于Firefox,Chrome和Safari,但我无法在Internet Explorer中对此进行测试。有人可以测试它,然后编辑我的答案或评论吗?
$(document).scrollTop(0);
答案 10 :(得分:4)
我的纯(动画)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
语句检查是否仍需要滚动。
答案 11 :(得分:3)
为什么不在html文件的最开头使用一些引用元素,比如
<div id="top"></div>
然后,当页面加载时,只需执行
$(document).ready(function(){
top.location.href = '#top';
});
如果浏览器在之后滚动,则此功能会触发,您只需执行
$(window).load(function(){
top.location.href = '#top';
});
答案 12 :(得分:3)
跨浏览器滚动到顶部:
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);
}
}
答案 13 :(得分:2)
如果你处于怪癖模式(感谢@Niet the Dark Absol):
document.body.scrollTop = document.documentElement.scrollTop = 0;
如果你处于严格模式:
document.documentElement.scrollTop = 0;
这里不需要jQuery。
答案 14 :(得分:2)
这两个的结合帮助了我。其他答案都没有帮助我,因为我的sidenav不能滚动。
setTimeout(function () {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
document.body.scrollTop = document.documentElement.scrollTop = 0;
}, 15);
答案 15 :(得分:2)
这是有效的:
jQuery(document).ready(function() {
jQuery("html").animate({ scrollTop: 0 }, "fast");
});
答案 16 :(得分:2)
在我的情况下,身体没有用:
$('body').scrollTop(0);
但HTML有效:
$('html').scrollTop(0);
答案 17 :(得分:2)
要回答您的编辑问题,您可以注册onscroll
处理程序,如下所示:
document.documentElement.onscroll = document.body.onscroll = function() {
this.scrollTop = 0;
this.onscroll = null;
}
这将使第一次滚动尝试(可能是浏览器自动完成)将被有效取消。
答案 18 :(得分:1)
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;"/>
答案 19 :(得分:1)
没有动画,只有scroll(0, 0)
(vanilla JS)
答案 20 :(得分:1)
如果有人使用有角度和材料设计的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;
});
答案 21 :(得分:1)
哇,我这个问题迟到了9年。在这里,您去了:
将此代码添加到您的加载中。
// 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.Cross-browser supported.
window.scrollTo(0,0);
history.scroll恢复浏览器支持:
Chrome:受支持(自46开始)
Firefox:受支持(自46开始)
IE / Edge:不支持(尚..)
Opera:受支持(自33开始)
Safari:受支持
对于IE / Edge,如果要在其自动向下滚动后重新滚动到顶部,则对我有用:
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
var isEdge = /Edge/.test(navigator.userAgent);
if(isIE11 || isEdge) {
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.
}
答案 22 :(得分:0)
适用于任何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();
}
答案 23 :(得分:0)
首先将空白锚标记添加到您要去的地方
<a href="#topAnchor"></a>
现在在标题部分添加一个函数
function GoToTop() {
var urllocation = location.href;
if (urllocation.indexOf("#topAnchor") > -1) {
window.location.hash = "topAnchor";
} else {
return false;
}
}
最后将一个onload事件添加到body标签
<body onload="GoToTop()">
答案 24 :(得分:0)
看到散列应该完成这项工作。如果您有标题,则可以使用
window.location.href = "#headerid";
否则,#单独工作
window.location.href = "#";
当它被写入网址时,如果你刷新它就会停留。
事实上,如果您想在onclick事件中执行此操作,则事件不需要JavaScript,您应该只在链接中放置一个链接并将其作为href。
答案 25 :(得分:0)
我记得看到这个贴在其他地方(我找不到位置),但这确实很好:
setTimeout(() => {
window.scrollTo(0, 0);
}, 0);
这很奇怪,但是它的工作方式基于JavaScript堆栈队列的工作方式。完整说明位于here的“零延迟”部分。
基本思想是setTimeout
的时间实际上并没有指定等待的设置时间,而是指定了等待的最短时间。因此,当您告诉它等待0毫秒时,浏览器将运行所有其他排队的进程(例如,将窗口滚动到您的最后一个位置),然后执行回调。
答案 26 :(得分:0)
答案 27 :(得分:-1)
<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>