简体   繁体   中英

Scroll to bottom of a div

I have a problem with scrolling a div to bottom with jQuery.

Div

HTML:

<div id="chatbox"></div>

CSS:

    #chatbox {
    width:300px;
    height:400px;
    background:grey;
    overflow-x:hidden;
    overflow-y:auto;
    border-radius: 10px;
    background: #045671;
}

when i use onclick -> $("#chatbox").scrollTop(9999) the scroll goes to bottom, the problem comes after clicking again the scroll goes +20px up.

EXAMPLE : http://46.238.10.232:10001/chat/

If you over-set scrollTop , magic happens (or doesn't, depending on your expectation). Setting scrollTop to 9999 will set the scrollTop to any number between 0 and 9999, depending on necessity. You can also read scrollTop , so setting it to x doesn't mean it will stay x , it will be the actual position, so that it still makes sense should you be interested in querying the value ever.

If the contents of the element change, you'll have to set scrollTop again. Usually to scrollHeight will always be sufficient (yes you could try to calculate scrollTop perfectly accurately, but why bother? Let the browser do the calculation, and get back to work).

So I guess, when you 'click again' (whatever that is), you're adding more content to your chatbox. Yes? Then you've got to set scrollTop , again !


If you are setting scrollTop every time, you're probably doing it too early. You should do it after you've modified the element's content, rather than merely in response to an onclick event.

$(document).scrollTop($("#chatbox").position.top+$("#chatbox").height());

The <a> tag might do the trick. I know it is pretty ugly, but with css you can style it as normal text or hide it entirely.

  1. Place a custom element where you want to scroll to.
  2. Set it's id to (for example) scrollelement .
  3. Set window.location.hash to 'scrollelement'.

Credits to Lee Kowalkowski.

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