使用 xhttp 加载页面

Loading a page with xhttp

本文关键字:加载 xhttp 使用      更新时间:2023-09-26

>我有一个小问题想问。

首先,我使用 JS 加载页面。

function ReLoad() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
         if (xhttp.readyState == 4 && xhttp.status == 200) {
             document.getElementById("box").innerHTML = xhttp.responseText;
          }
       };
      xhttp.open("GET", "calc/index.html", true);
      xhttp.send();
 }

现在,我的问题是当我将此索引插入主页时,因为页面会立即自动滚动到开头,并且我想加载页面而不会产生这种烦人的效果。

拜托,有人可以帮我吗?谢谢

您可以存储滚动位置;

var currentPosition = window.pageYOffset || document.documentElement.scrollTop;

并重新应用它:

window.scrollTo(0, currentPosition);

所以你的代码会变成:

function ReLoad() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
     if (xhttp.readyState == 4 && xhttp.status == 200) {
         var currentPosition = window.pageYOffset || document.documentElement.scrollTop;
         document.getElementById("box").innerHTML = xhttp.responseText;
         window.scrollTo(0, currentPosition);
      }
   };
  xhttp.open("GET", "calc/index.html", true);
  xhttp.send();
}

我终于解决了它,并将其添加到代码末尾:

e.preventDefault();
return false;