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

javascript - Css scroll bar auto scrolling with added content - Stack Overflow

programmeradmin2浏览0评论

I have div with fixed width and height. Div contains unordered list and has css overflow-y: scroll property. In javascript I have function which triggers when user click button below list, and that function adds one list item. When there is too much content inside div, new list items are added at the bottom of list and user needs to scroll list in order to see new list items. Is it possible somehow to make scroll bar auto scroll along with new content added, so that last added list item would be always visible?

Html:

<ul id="scroll">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
<button type="button" id="click">Click</button>

Css:

ul {
  height: 100px;
  width: 100px;
  overflow-y: scroll;
  border: 1px solid black;
}

Javascript:

function addListItem(){
    var message = document.createElement('li');
  message.innerHTML = 'd';

  document.getElementById('scroll').appendChild(message);
}

document.getElementById('click').addEventListener('click', addListItem, true);

JS fiddle link: /

I have div with fixed width and height. Div contains unordered list and has css overflow-y: scroll property. In javascript I have function which triggers when user click button below list, and that function adds one list item. When there is too much content inside div, new list items are added at the bottom of list and user needs to scroll list in order to see new list items. Is it possible somehow to make scroll bar auto scroll along with new content added, so that last added list item would be always visible?

Html:

<ul id="scroll">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
<button type="button" id="click">Click</button>

Css:

ul {
  height: 100px;
  width: 100px;
  overflow-y: scroll;
  border: 1px solid black;
}

Javascript:

function addListItem(){
    var message = document.createElement('li');
  message.innerHTML = 'd';

  document.getElementById('scroll').appendChild(message);
}

document.getElementById('click').addEventListener('click', addListItem, true);

JS fiddle link: https://jsfiddle/8gjhatvt/2/

Share asked Aug 11, 2016 at 20:33 FurmanFurman 2,4635 gold badges37 silver badges52 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Set the Element.scrollTop property of the scrolling div to be the position of the new element in the page + the new element's offset in its parent.

For example in the addListItem() function add the following line:

document.getElementById('scroll').scrollTop = message.offsetHeight + message.offsetTop; 

Working fiddle: https://jsfiddle/rvnj6mc3/

Add this code to addListItem() function:

var scroll=document.getElementById("scroll");
scroll.scrollTop = scroll.scrollHeight;
发布评论

评论列表(0)

  1. 暂无评论