简体   繁体   English

滚动回可滚动 div 的顶部

[英]Scroll back to the top of scrollable div

<div id="containerDiv"></div>
#containerDiv {
  position: absolute;
  top: 0px;
  width: 400px;
  height: 100%;
  padding: 5px;
  font-size: .875em;
  overflow-y: scroll;
}
document.getElementById("containerDiv").innerHTML = variableLongText;

How to reset the scroll position back to top of container div the next time?下次如何将滚动位置重置回容器 div 的顶部?

var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;

See the scrollTop attribute.请参阅scrollTop属性。

另一种使用平滑动画的方法是这样的

$("#containerDiv").animate({ scrollTop: 0 }, "fast");

I tried the existing answers to this question, and none of them worked on Chrome for me.我尝试了这个问题的现有答案,但没有一个适合我在 Chrome 上工作。 What did work was slightly different:工作的内容略有不同:

$('body, html, #containerDiv').scrollTop(0);

这对我有用:

document.getElementById('yourDivID').scrollIntoView();

scrollTo滚动到

window.scrollTo(0, 0);

is the ultimate solution for scrolling the windows to the top - the best part is that it does not require any id selector and even if we use the IFRAME structure it will work extremely well.是将窗口滚动到顶部的最终解决方案 - 最好的部分是它不需要任何 id 选择器,即使我们使用 IFRAME 结构,它也能很好地工作。

The scrollTo() method scrolls the document to the specified coordinates. scrollTo() 方法将文档滚动到指定的坐标。
window.scrollTo(xpos, ypos); window.scrollTo(xpos, ypos);
xpos Number Required. xpos 号码 必填。 The coordinate to scroll to, along the x-axis (horizontal), in pixels沿 x 轴(水平)滚动到的坐标,以像素为单位
ypos Number Required. ypos 编号 必填。 The coordinate to scroll to, along the y-axis (vertical), in pixels沿 y 轴(垂直)滚动到的坐标,以像素为单位

jQuery jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same做同样的另一个选择是使用 jQuery,它会给相同的外观更流畅

$('html,body').animate({scrollTop: 0}, 100);

where 0 after the scrollTop specifies the vertical scrollbar position in the pixel and second parameter is an optional parameter which shows the time in microseconds to complete the task.其中 scrollTop 后面的 0 指定像素中的垂直滚动条位置,第二个参数是可选参数,显示完成任务的时间(以微秒为单位)。

For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function .对于仍然无法完成这项工作的人,请确保在使用 jQuery 函数之前显示溢出的元素

Example:例子:

$('#elem').show();
$('#elem').scrollTop(0);

2020 UPDATE 2020 更新

You can use .scroll() to easily scroll elements or window.您可以使用.scroll()轻松滚动元素或窗口。 It has a built-in smooth scroll effect so basically the code couldn't be simpler.它有一个内置的平滑滚动效果,所以基本上代码再简单不过了。

Standard properties:标准属性:

var options = {
    top:       0,        // Number of pixels along the Y axis to scroll the window or element
    left:      0,        // Number of pixels along the X axis to scroll the window or element.
    behavior:  'smooth'  // ('smooth'|'auto') - animate smoothly, or move in a single jump
}

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

SEE ALSO: .scrollIntoView() https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView .scrollIntoView()见: .scrollIntoView() https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView


DEMO:演示:

 document.getElementById('btn').addEventListener('click',function(){ document.getElementById('container').scroll({top:0,behavior:'smooth'}); });
 /*DEMO*/ #container{ width:300px; max-height:300px; padding:1rem; margin-left:auto; margin-right:auto; background-color:#222; color:#ccc; text-align:justify; overflow-y:auto; } #btn{ width:100%; margin-top:1rem; }
 <div id="container"> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> <button id="btn">Scroll to top</button> </div>

If you want to scroll with a smooth transition, you could use this!如果你想平滑过渡滚动,你可以使用这个!

(Vanilla JS) (香草JS)

const tabScroll = document.getElementById("tabScroll");
window.scrollTo({
  'behavior': 'smooth',
  'left': 0,
  'top': tabScroll.offsetTop - 80
});

If your target users are Chrome and Firefox , then this is good!如果您的目标用户是ChromeFirefox ,那么这很好! But unfortunately this method isn't supported well enough on all browsers.但不幸的是,这种方法在所有浏览器上都没有得到足够的支持。 Check Here检查这里

Hope this helps!!希望这可以帮助!!

When getting element by class name, don't forget the return value is an array;按类名获取元素时,不要忘记返回值是一个数组; Hence this code:因此这个代码:

document.getElementByClassName("dropdown-menu").scrollTop = 0

Would not work.行不通。 Use code below instead.请改用下面的代码。

document.getElementByClassName("dropdown-menu")[0].scrollTop = 0

I figured other people might encounter a similar problem as I did;我想其他人可能会遇到和我一样的问题; so this should do the trick.所以这应该可以解决问题。

For me the scrollTop way did not work, but I found other:对我来说, scrollTop 方式不起作用,但我发现了其他方式:

element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);

Did not check the minimum time for reliable css rendering though, 100ms might be overkill.虽然没有检查可靠 css 渲染的最短时间,但 100 毫秒可能有点过头了。

As per François Noël's answer "For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function."根据 François Noël 的回答“对于那些仍然无法完成这项工作的人,请确保在使用 jQuery 函数之前显示溢出的元素。”

I had been working in a bootstrap modal that I repeatedly bring up with account permissions in a div that overflows on the y dimension.我一直在使用引导模式工作,我在 y 维度上溢出的 div 中反复提出帐户权限。 My problem was, I was trying to use the jquery .scrollTop(0) function and it would not work no matter how I tried to do it.我的问题是,我试图使用 jquery .scrollTop(0) 函数,无论我如何尝试它都无法工作。 I had to setup an event for the modal that didn't reset the scrollbar until the modal had stopped animating.我必须为模态设置一个事件,该事件在模态停止动画之前不会重置滚动条。 The code that finally worked for me is here:最终对我有用的代码在这里:

    $('#add-modal').on('shown.bs.modal', function (e) {
        $('div.border').scrollTop(0);
    });

This is the only way it worked for me, with smooth scrolling transition:这是它对我有用的唯一方法,具有平滑的滚动过渡:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);

ID 应该具有具有溢出 css 属性的相应 div 的 id。

document.querySelector('#YOUR_OVERFLOWED_DIV').scrollTop = 0;

If the html content overflow a single viewport, this worked for me using only javascript:如果 html 内容溢出单个视口,这对我只使用 javascript 有用:

document.getElementsByTagName('body')[0].scrollTop = 0;

Regards,问候,

these two codes worked for me like a charm this first will take to scroll to the top of the page but if you want to scroll to some specific div use the second one with your div id.这两个代码对我来说就像一个魅力,这首先将滚动到页面顶部,但如果你想滚动到某个特定的 div,请使用带有你的 div id 的第二个代码。

$('body, html, #containerDiv').scrollTop(0);
document.getElementById('yourDivID').scrollIntoView();

If you want to scroll to by a class name use the below code如果要按类名滚动到,请使用以下代码

var $container = $("html,body");
var $scrollTo = $('.main-content');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300);

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

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