html刷新页面停留在当前位置
时间: 2024-05-12 18:16:31 浏览: 17
要在HTML中刷新页面并停留在当前位置,您可以使用JavaScript来实现此操作。以下是实现此操作的一些示例代码:
方法一:
```html
<!DOCTYPE html>
<html>
<head>
<title>Refresh page and stay at current position</title>
<script>
function refreshPage() {
location.reload();
window.scrollTo(0, window.pageYOffset);
}
</script>
</head>
<body>
<p>This is some long content that requires scrolling!</p>
<button onclick="refreshPage()">Refresh Page</button>
</body>
</html>
```
在这个示例中,我们使用`location.reload()`方法来刷新页面,并使用`window.scrollTo()`方法将页面滚动到当前位置(使用`window.pageYOffset`获取当前垂直滚动位置)。
方法二:
```html
<!DOCTYPE html>
<html>
<head>
<title>Refresh page and stay at current position</title>
<script>
function refreshPage() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var url = window.location.href.split('#')[0];
window.location.replace(url + '#' + scrollTop);
location.reload();
}
window.onload = function() {
if (window.location.hash) {
var scrollTop = window.location.hash.substring(1);
window.scrollTo(0, scrollTop);
}
}
</script>
</head>
<body>
<p>This is some long content that requires scrolling!</p>
<button onclick="refreshPage()">Refresh Page</button>
</body>
</html>
```
在这个示例中,我们将当前垂直滚动位置存储在URL的哈希部分中,并在刷新页面后使用`window.scrollTo()`方法将页面滚动到保存的位置。我们还使用`window.onload`事件来检查页面是否包含哈希,如果是,则滚动到保存的位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)