Scroll back to the top of div

2019-01-16 13:24发布

<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?

11条回答
劫难
2楼-- · 2019-01-16 14:15

For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function.

Exemple:

$('#elem').show();
$('#elem').scrollTop(0);
查看更多
冷血范
3楼-- · 2019-01-16 14:21

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.

The scrollTo() method scrolls the document to the specified coordinates.
window.scrollTo(xpos, ypos);
xpos Number Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos Number Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same

$('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.

查看更多
The star\"
4楼-- · 2019-01-16 14:22

I tried the existing answers to this question, and none of them worked on Chrome for me. What did work was slightly different:

$('body, html, #containerDiv').scrollTop(0);
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-16 14:22

For me the scrollTop way did not work, but I found other:

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.

查看更多
走好不送
6楼-- · 2019-01-16 14:22

If you want to scroll with a smooth transition, you could use this!

(Vanilla 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! But unfortunately this method isn’t supported well enough on all browsers. Check Here

Hope this helps!!

查看更多
登录 后发表回答