admin管理员组

文章数量:1315225

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

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

Share Improve this question edited Apr 28, 2018 at 9:14 user9674579 asked Apr 28, 2018 at 9:09 betchibetchi 912 silver badges5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

本文标签: javascriptHow can I keep scroll position when add dom to topStack Overflow