简体   繁体   English

使用 Javascript 更改内容后滚动到 div 底部

[英]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.出于某种原因,在使用 Ajax 刷新其内容后,滚动到 div 底部的方法对我不起作用。

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.我认为这个问题与 DOM 的工作方式有关——例如,当它进行更改时,但是,我对 javascript 或 DOM 了解不够,无法真正理解这将如何干扰滚动到底部。

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?谁能建议一种在 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:刷新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?刷新div后调用滚动到底部的正确位置是什么?

use this script to scroll to bottom of div使用此脚本滚动到 div 的底部

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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