简体   繁体   English

将dom添加到顶部时如何保持滚动位置

[英]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. 当将DOM添加到父DOM的顶部时,我遇到了滚动位置的问题。 The scroll position is automatically set to the top when the scroll position is at the top(targetDOM.scrollTop == 0). 当滚动位置位于顶部时,滚动位置将自动设置为顶部(targetDOM.scrollTop == 0)。

This problem does not occur if the scroll position is 1 or more(targetDOM.scrollTop > 0). 如果滚动位置为1或更大(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 示例添加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 在Chrome和FF上测试

codepen 码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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