javascript - 刷新主页内的页面时防止div在顶部滚动
问题描述
我是 javascript 新手,我正在做我的项目。我这里有两个页面,第一个是 home.php,这里是调用 data.php 并每 3 秒刷新一次的代码:
<div id="show"></div>
<script type="text/javascript">
function reload()
{
$("#show").load("data.php");
}
$(function() {
setInterval(reload, 3000);
});</script>
在 data.php 中,这是我的代码:
<div class = "table-container" id = "table-container">
echo '<table class = "track" name = "allData" id = "allData">
<tr style">
<th> Device ID </th>
<th> Name </th>
<th> Date and Time </th>
<th> latitude </th>
<th> longitude </th>
<th> Contact Number </th>
<th> Age </th>
<th> Track </th>
<th> Status </th>
</tr>';
$sql = "SELECT d.deviceID, CONCAT(u.lastName, ', ', u.firstName) AS Name, t.dateTime, t.latitude, t.longitude, u.contactNumber, u.age, t.status
FROM tbltracking as t
LEFT OUTER JOIN tbldevicemaster as d
ON t.deviceID = d.deviceID
LEFT OUTER JOIN tblusers as u
ON d.userID = u.userID
ORDER BY dateTime;";
$result = $conn-> query($sql);
$number = $result -> num_rows;
if ($result-> num_rows > 0)
{
while ($row = $result-> fetch_assoc())
{
echo
"<tr><td>"
. $row ["deviceID"]
."</td><td class = 'name'>"
. $row ["Name"]
."</td><td>"
. $row ["dateTime"]
."</td><td class = 'latitude'>"
. $row ["latitude"]
."</td><td class = 'longitude'>"
. $row ["longitude"]
."</td><td>"
. $row ["contactNumber"]
."</td><td>"
. $row ["age"]
."</td><td>"
.'<button type = "button" class = "a"> Select</button>'
."</td><td>" .$row["status"]
."</td></tr>";
}
echo "</table>";
echo "</div>";
这是表格容器的 CSS:
.table-container
{
overflow-y: scroll;
height: 170px;
display: block;
width: 100%;
}
所以是的,在 home.php 中,data.php 窗口可以显示在 div id "show" 内,并且每 3 秒刷新一次,以便页面再次运行查询。问题是,当我在 home.php 时,每当我尝试滚动表格并刷新时,滚动条就会出现在顶部。
就像我说的,我对编程比较陌生,所以任何人都可以帮助我吗?
我还尝试了另一个代码,当我只在 data.php 页面并手动刷新页面时该代码有效。该方法将其存储到本地存储。以下是 data.php 中的部分代码:
<script>
window.addEventListener("beforeunload", () => {
localStorage.setItem("scrollPositon", document.querySelector(".table-container").scrollTop);
});
window.addEventListener("load", () => {
document.querySelector(".table-container").scrollTop = localStorage.getItem("scrollPositon") || 0;
});
</script>
解决方案
有一种方法可以重新加载 data.php 内容并保持滚动位置,问题是由于您的表格高度,每 3 秒刷新一次,所以您需要做的是将表格容器和表格标签从数据中取出.php 像这样:
(在home.php内)
<div class="table-container">
<table class="track" name="allData" id="show"> <!-- ID: show -->
</table>
</div>
<script>
var auto_refresh = setInterval(
(function () {
$("#show").load("data.php"); //Load the content into the div
}), 3000);
</script>
在你的data.php里面:
echo '<tr style">
<th> Device ID </th>
...
...
etc..
...
...
."</td><td>" .$row["status"]
."</td></tr>";
}
这将在每次重新加载时保持滚动位置,如果你想在其他地方显示 data.php 内容,你必须添加 table-container 和 table 标签,就像我在 home.php 中展示的那样。