简体   繁体   中英

Scroll to bottom of div after changing contents using Javascript

For some reason the methods to scroll to bottom of div are not working for me after refreshing its contents using Ajax.

I think the issue has something to do with how the DOM works--eg when it makes its changes, however, I don't know enough about javascript or the DOM to really understand how that would interfere with scrolling to bottom.

So I think the issue is when and how to call the methods rather than the methods themselves. Can anyone suggest a way to scroll to bottom after the refresh of div?

Methods to scroll to bottom I am trying:

Method 1:

var element = document.getElementById("chatBox");
    element.scrollTop = element.scrollHeight;

Method 2:

document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });

Method that refreshes div:

function refreshDiv() { 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
alert("got 200");
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
alert("will now try to update Scroll");
//FOLLOWING HAS NO EFFECT POSSIBLY BECAUSE DOM HAS NOT YET RETURNED RESULTS
document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });
    }
  }
xmlhttp.open("GET","refreshDiv.php,true);
xmlhttp.send();

return;
//THIS ALSO HAS NO EFFECT POSSIBLY AS IT IS AFTER RETURN
document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });
  }

What is the proper place to call scroll to bottom after refreshing div?

use this script to scroll to bottom of div

    var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

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