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 13:55

This worked for me :

document.getElementById('yourDivID').scrollIntoView();
查看更多
\"骚年 ilove
3楼-- · 2019-01-16 13:58

Another way to do it with a smooth animation is like this

$("#containerDiv").animate({ scrollTop: 0 }, "fast");
查看更多
做自己的国王
4楼-- · 2019-01-16 13:59

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."

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. 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. 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);
    });
查看更多
女痞
5楼-- · 2019-01-16 14:06
var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;

See the scrollTop attribute.

查看更多
等我变得足够好
6楼-- · 2019-01-16 14:09

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.

$('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);
查看更多
女痞
7楼-- · 2019-01-16 14:14

If the html content overflow a single viewport, this worked for me using only javascript:

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

Regards,

查看更多
登录 后发表回答