有没有办法用 JavaScript/jQuery 控制浏览器滚动?
当我将页面向下滚动一半,然后触发重新加载时,我希望页面打包到顶部,但它却试图找到最后一个滚动位置。所以我这样做了:
$('document').ready(function() {
$(window).scrollTop(0);
});
但没有运气。
编辑:
因此,当我在页面加载后给他们打电话时,您的两个答案都有效-谢谢。但是,如果我只是在页面上进行刷新,看起来浏览器会在 .ready
事件之后计算并滚动到它的旧滚动位置(我也测试了 body 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。
// 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.
}
更新
现在在 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>
干杯!
有没有办法阻止浏览器滚动到它过去的位置,或者在它完成它之后重新滚动到顶部?
以下 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>
requestAnimationStep
而不是 setTimeout
。它也没有回答 OP 的问题。
这对我有用:
window.onload = function() {
// short timeout
setTimeout(function() {
$(document.body).scrollTop(0);
}, 15);
};
在 onload
中使用一个短的 setTimeout
让浏览器有机会进行滚动。
您可以使用 jQuery
jQuery(window).load(function(){
jQuery("html,body").animate({scrollTop: 100}, 1000);
});
使用以下功能
window.scrollTo(xpos, ypos)
这里 xpos 是必需的。沿 x 轴(水平)滚动到的坐标,以像素为单位
ypos 也是必需的。沿 y 轴(垂直)滚动到的坐标,以像素为单位
document.body.scrollIntoView({behavior: "smooth"});
适用于包括 IE 在内的所有浏览器(旧版浏览器不支持平滑滚动)。
https://i.stack.imgur.com/K5xwc.png
$(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);
}
);
});
用这个
以下代码适用于 Firefox、Chrome 和 Safari,但我无法在 Internet Explorer 中对此进行测试。有人可以测试它,然后编辑我的答案或评论它吗?
$(document).scrollTop(0);
为什么不在 html 文件的开头使用一些参考元素,比如
<div id="top"></div>
然后,当页面加载时,只需执行
$(document).ready(function(){
top.location.href = '#top';
});
如果此函数触发后浏览器滚动,您只需执行
$(window).load(function(){
top.location.href = '#top';
});
我的纯(动画)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
语句检查我们是否仍需要滚动。
跨浏览器滚动到顶部:
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。
在我的情况下,身体没有工作:
$('body').scrollTop(0);
但 HTML 工作:
$('html').scrollTop(0);
'html','body'
添加为现代浏览器 FF,Chrome 将根据 body 滚动,但 IE8 及以下版本将仅使用 'html','body'
滚动
要回答您编辑的问题,您可以像这样注册 onscroll
处理程序:
document.documentElement.onscroll = document.body.onscroll = function() {
this.scrollTop = 0;
this.onscroll = null;
}
这将使第一次滚动尝试(可能是浏览器自动完成)将被有效取消。
这是有效的:
jQuery(document).ready(function() {
jQuery("html").animate({ scrollTop: 0 }, "fast");
});
这两者的结合帮助了我。因为我有一个不滚动的sidenav,所以其他答案都没有帮助我。
setTimeout(function () {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
document.body.scrollTop = document.documentElement.scrollTop = 0;
}, 15);
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)
(vanilla 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;
});
Seeint 哈希应该可以完成这项工作。如果你有一个标题,你可以使用
window.location.href = "#headerid";
否则,单独的 # 将起作用
window.location.href = "#";
当它被写入 url 时,如果你刷新它就会留下来。
事实上,如果您想在 onclick 事件上执行此操作,则不需要 JavaScript,您只需在元素周围放置一个链接并将其 # 作为 href。
首先在你想去的地方添加一个空白的锚标签
<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 堆栈队列的工作方式。完整的解释可在零延迟部分找到 here。
基本思想是 setTimeout
的时间实际上并没有指定它要等待的设定时间,而是它要等待的最短时间。因此,当您告诉它等待 0 毫秒时,浏览器会运行所有其他排队的进程(例如将窗口滚动到您上次所在的位置),然后执行回调。
不定期副业成功案例分享
$(window).one("scroll",function() { /* the code from my answer here */ });