最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I keep scroll position when add dom to top - Stack Overflow

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论