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 badges1 Answer
Reset to default 9You 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
版权声明:本文标题:javascript - How can I keep scroll position when add dom to top - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741973517a2407983.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论