使用 JavaScript 刷新浏览器后如何在一个页面网站中保存部分位置?
Posted
技术标签:
【中文标题】使用 JavaScript 刷新浏览器后如何在一个页面网站中保存部分位置?【英文标题】:How to save section position in one page website after browser refresh with JavaScript? 【发布时间】:2022-01-18 17:46:49 【问题描述】:这是一个单页index.html
网站。即使在浏览器刷新后,我也想固定每个部分的位置。如何修改 main.js
以获取此更改所需的 javascript 代码?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Page Title</title>
<meta name="description" content="My Page Description">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<section class="home-section"> </section>
<section class="about-section"> </section>
<section class="gallary-section"> </section>
<section class="project-section"> </section>
<section class="testimonial-section"> </section>
<section class="contact-section"> </section>
<script src="js/scripts.js"></script>
</body>
</html>
【问题讨论】:
每次用户更改部分(滚动位置?)时,您会将其保存到 localStorage 中,然后在刷新后查看是否存在 localStorage 并滚动到该值。 @SimoneRossaini 一些演示代码会有很大帮助。你能展示一些演示吗? current Element in view - localStorage 【参考方案1】:你可以这样做:
const currentURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
let sections = document.querySelectorAll('.sec')
sections.forEach(function(item)
window.addEventListener("scroll",()=>
if(isScrolledIntoView(item))
window.history.replaceState("", item.id , `$currentURL#$item.id`);
)
)
// this is not my code, found it in ***
function isScrolledIntoView(elem)
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
.sec
width: 100%;
height:400px;
border: 1px solid black;
display: flex;
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Page Title</title>
<meta name="description" content="My Page Description">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- <link rel="stylesheet" href="css/styles.css?v=1.0"> -->
</head>
<body>
<section class="home-section sec" id="sec1"> section1 </section>
<section class="about-section sec" id="sec2"> section2 </section>
<section class="gallary-section sec" id="sec3" > section3 </section>
<section class="project-section sec" id="sec4"> section4 </section>
<section class="testimonial-section sec" id="sec5"> section5 </section>
<section class="contact-section sec" id="sec6"> section6 </section>
<!-- <script src="js/scripts.js sec" id="sec7"></script> -->
</body>
</html>
【讨论】:
以上是关于使用 JavaScript 刷新浏览器后如何在一个页面网站中保存部分位置?的主要内容,如果未能解决你的问题,请参考以下文章