I am currently working on a project that will not allow for jQuery and I am very new to JavaScript and OO programming as a whole (Two weeks). You can see the entirety of the project in the following repo: https://github.com/Sntax/jsChat/blob/master/script.js

Basically I am creating a simple chat app as a learning project. I am injecting HTML into a div onClick or Enter/Tab using:

var jsChat = {
  username: document.getElementById('username'),
  comment: document.getElementById('comment'),
  output: document.getElementById('output'),
};

function postData(){
  jsChat.output.innerHTML += '<div class="username">' + jsChat.username.value + ':' + '</div>';
  jsChat.output.innerHTML += '<div class="comment">' + jsChat.comment.value + '</div>';
  clearContent();
}

Right now it will print to the div successfully but once the "comments" become too long for the div-height, they will auto scroll off the bottom of the page and out of sight. I am wanting to setup a way to force the scroll to "scroll down" to the bottom of the div so that it rather scrolls old chat comments off the top of screen much like a normal chat application.

Ninja Edit: I tried throwing the following into the postData() function to no avail:

    jsChat.output.scrollTop = 99999;
有帮助吗?

解决方案

You can use the scrollTo function, as follows:

window.scrollTo(DOMNodeOfMyNewMessage.offsetTop,window.scrollY);

This will scroll the latest message to the top of the screen.

However, you’ll probably want to scroll the page just by the height of the new comment. That is possible too, using the scrollBy function and the element’s offsetHeight:

window.scrollBy(DOMNodeOfMyNewMessage.offsetHeight, window.scrollY);

The final code might look somewhat like the following:

var jsChat = {
  username: document.getElementById('username'),
  comment: document.getElementById('comment'),
  output: document.getElementById('output'),
},
latestMessage;//DOM Node of my new message

function postData(){
  latestMessage = document.createElement('div');
  latestMessage.innerHTML = '<div class="username">' + jsChat.username.value + ':</div>' +
  '<div class="comment">' + jsChat.comment.value + '</div>';
  clearContent();//Not sure what this does, check if you still need it with this code
  latestMessage = jsChat.output.appendChild(latestMessage);// appendChild: see https://developer.mozilla.org/docs/Web/API/Node.appendChild
  //Now we scroll the message into view
  window.scrollBy(latestMessage.offsetHeight, window.scrollY);
}

其他提示

After posting the comment into output:

var last_comment_index = jsChat.comment.length - 1;
jsChat.output.scrollTop = jsChat.comment[last_comment_index].offsetTop;

This will scroll to the last comment. Hope that helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top