如何防止在AJAX中重置滚动?

我有一个div容器,该容器通过javascript函数每3秒修改一次其内容,该功能最初是通过body标签的onload事件调用的。

function showNow(){

    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) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
   };

   xmlhttp.open("GET", "tab.php", true);
   xmlhttp.send();

   setTimeout(showNow, 3000);
}

但每3秒刷新一次内容,这会导致滚动位置重置,因此我的页面跳回到了开始,极大地影响了可用性。

有人可以提出解决方案吗?

Before the innerHTML is set, you could get the txtHint element's scrollTop property. Then, after the text is added, set that variable to scrollTop again.

if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
    var scroll = document.body.scrollTop;
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    document.body.scrollTop = scroll;
 }

You can use window.scrollTo(x, y) to set the position of scroll, for sample:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
   window.scrollTo(0, 0); //stay on the top
}

try adding

return false;

at end of the ajax request

I'm french so forgive me for my bad English

I had the same thing on my page : when I clicked on the link, the XHR request reseted my scroll on full top. I've found my mistake...a very stupid one... Check your HTML, if your "onClick" is in a <a> tag, check you've not written <a href="#" onClick="myFunction()">... That was my mistake, and just <a onClick="myFunction()"> don't reset the scroll x)

Hope I've helped you

Not sure this was answered completely.

I had the same problem, trying all solutions above did not solve it. What i found was that refreshing the innerHTML actually made the Scrollbar disappear for a very short period of time (because the entire page becomes a lot smaller in height as the content gets refreshed), subsequently when content reappears (and the Scrollbar) the browser has no way of knowing where he was before the call and hence scrolls all the way up.

My own solution was very simple and does not involve catching events etc..., I added a column which I filled with a spacer.gif the height of the div I intend to refresh. That way the entire page layout itself never actually gets distorted, the Scrollbar never disappear even a short period of time.

<table width="30%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td>
    <img src="/images/spacer.gif" width="0" height="170"/>   <-- adding the extra column to keep the height always the same.
    </td>
    <td>
      <div id="content">
        <script>loadnewusermenu()</script> <-- content getting refreshed
      </div>
    </td>
  </tr>
</table>

Hope it makes sense. DjYoy