有没有办法用JavaScript / jQuery控制浏览器滚动?
当我将页面向下滚动一半,然后触发重新加载时,我希望页面打包到顶部,而是尝试查找最后一个滚动位置。所以我这样做了:
$('document').ready(function() {
$(window).scrollTop(0);
});
但没有运气。
编辑:
因此,当我在页面加载后调用它们时,你的答案都有效 - 谢谢。但是,如果我只是在页面上刷新,看起来浏览器计算并滚动到.ready
事件之后的旧滚动位置(我也测试了body onload()函数)。
那么跟进是,有没有办法防止浏览器滚动到它的过去位置,或者重新滚动到它做它的事情之后的顶部?
跨浏览器,纯JavaScript解决方案:
document.body.scrollTop = document.documentElement.scrollTop = 0;
以下代码适用于Firefox,Chrome和Safari,但我无法在Internet Explorer中对此进行测试。有人可以测试它,然后编辑我的答案或评论吗?
$(document).scrollTop(0);
我的纯(动画)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
语句检查我们是否仍需要滚动。
你为什么不在你的html文件的最开头使用一些引用元素,比如
<div id="top"></div>
然后,当页面加载时,只需执行
$(document).ready(function(){
top.location.href = '#top';
});
如果浏览器在此功能触发后滚动,您只需执行此操作即可
$(window).load(function(){
top.location.href = '#top';
});
跨浏览器滚动到顶部:
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);
}
}
在我的情况下,身体没有工作:
$('body').scrollTop(0);
但HTML工作:
$('html').scrollTop(0);
要回答您编辑过的问题,您可以像这样注册onscroll
处理程序:
document.documentElement.onscroll = document.body.onscroll = function() {
this.scrollTop = 0;
this.onscroll = null;
}
这将使得第一次滚动尝试(可能是浏览器完成的自动操作)将被有效取消。
如果你处于怪癖模式(感谢@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");
});
这两者的结合帮助了我。没有其他答案帮助我,因为我有一个不滚动的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;"/>
你几乎得到它 - 你需要在scrollTop
上设置body
,而不是window
:
$(function() {
$('body').scrollTop(0);
});
编辑:
也许你可以在页面顶部添加一个空白锚点:
$(function() {
$('<a name="top"/>').insertBefore($('body').children().eq(0));
window.location.hash = 'top';
});
没有动画,只有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;
});
看到哈希应该做的工作。如果您有标题,则可以使用
window.location.href = "#headerid";
否则,#单独行动
window.location.href = "#";
当它被写入网址时,如果你刷新它就会留下来。
事实上,如果您想在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>
有没有办法防止浏览器滚动到其过去的位置,或重新滚动到顶部它做它的事情后?
以下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>
UPDATE
使用滚动效果转到页面顶部在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
等。
老答复
这是我们的香草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>
干杯!
这对我有用:
window.onload = function() {
// short timeout
setTimeout(function() {
$(document.body).scrollTop(0);
}, 15);
};
在setTimeout
中使用一个短的onload
,让浏览器有机会进行滚动。
你可以使用jQuery
jQuery(window).load(function(){
jQuery("html,body").animate({scrollTop: 100}, 1000);
});
使用以下功能
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);
}
);
});
用这个