简体   繁体   中英

How to scroll div-element acting as a chat window to its bottom?

I have prepared a jsFiddle for my question:

截屏

I am trying to use a (yellow) div element for a chat in a multiplayer game.

Unfortunately, the div does not scroll to the most recent line that I append() to it.

 $('#chatBtn').button().click(function(e) { e.preventDefault(); var str = $('#chatInput').val(); $('#chatInput').val(''); $('#chatDiv').append('<br>' + str); var h = $('#chatDiv').attr('scrollHeight'); //$('#chatDiv').scrollTop(h); $('#chatDiv').animate({ // DOES NOT SCROLL TO DIV BOTTOM, WHY? scrollTop: h }, 1000); }); $('#chatInput').on('input', function(e) { // ENABLES/DISABLES BUTTON, WORKS OK var str = $('#chatInput').val(); $('#chatBtn').button(str.length > 0 ? 'enable' : 'disable'); });
 @import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css"); div#chatDiv { margin: 0 auto; background-color: yellow; width: 400px; height: 100px; overflow: auto; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script> <div id="chatDiv"></div> <p align="center"> <input id="chatInput" type="text" size="40" /> <button id="chatBtn" disabled>Send</button> </p>

Please enter 4-5 words into chatInput and click the chatBtn each time - and you will see the problem: the bottom lines are not shown, the chatDiv -element is not scrolled down.

Following line is not giving height

var h = $('#chatDiv').attr('scrollHeight');

Replace above line of code with

var h =$('#chatDiv').prop('scrollHeight');

Rather than using input event you can put one condition on button click

$(document).ready(function() {
     $('#chatBtn').click(function(e) {
         e.preventDefault();   
         var str = $('#chatInput').val().trim();
          if(str !== ''){
              $('#chatInput').val('');
              $('#chatDiv').append('<br>' + str);
              var h =$('#chatDiv').prop('scrollHeight');
              $('#chatDiv').animate({
                 scrollTop: h
              }, 1000);
           }
        });
   });

If you remove input event then don't forget to remove disabled from button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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