简体   繁体   中英

How can I keep scroll position when add dom to top

I am suffering from the problem of the scroll position when DOM is added to the top of the parent DOM. The scroll position is automatically set to the top when the scroll position is at the top(targetDOM.scrollTop == 0).

This problem does not occur if the scroll position is 1 or more(targetDOM.scrollTop > 0).

I want to prevent the scroll position from becoming the top automatically if the scroll position is top.

Is there a solution?

example add DOM

var i = 1;
function addDom(){
  var content = document.getElementById('content');
  for (j = i; j <= i + 9; j++) {
    var dom = document.createElement('div');
    dom.innerHTML= j;
    content.appendChild(dom);
    content.insertBefore(dom, content.firstChild);
  }
  i = j;
}

codepen

You should save current scroll position and scroll size. Then add elements. Get new scroll size and set scroll position to old position plus (new scroll size minus old scroll size):

var i = 1;
function addDom(){
  var content = document.getElementById('content');

  var curScrollPos = content.scrollTop;
  var oldScroll = content.scrollHeight - content.clientHeight;

  for (j = i; j <= i + 9; j++) {
    var dom = document.createElement('div');
    dom.innerHTML= j;
    content.appendChild(dom);
    content.insertBefore(dom, content.firstChild);
  }

  var newScroll = content.scrollHeight - content.clientHeight;
  content.scrollTop = curScrollPos + (newScroll - oldScroll);

  i = j;
}

Tested on Chrome and FF

codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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