我是一个新手,了解 HTML5 和 CSS3,但不太了解 JavaScript。当我在网站上的不同页面之间单击时,我试图将浏览器保持在相同的滚动位置。这些页面是 illustration.html、design.html 和小册子.html。每次加载新页面时跳回到顶部变得有点令人沮丧。下面是我的 HTML5 示例。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="../js/browser.js" type="text/javascript"></script>
</head>
<body>
<section>
<header><title>design</title></header>
<article>
<div id="illustration">
<a href="illustration.html">illustration</a>
</div>
<div id="design">
<a href="#">design</a>
</div>
<div id="brochures">
<a href="brochure.html">brochures</a>
</div>
</article>
</section>
</body>
</html>
是否有一段简单的 JavaScript 可以在页面之间单击时保持滚动位置不变?
最佳答案
不是真的。试试这个,把它放在你的收盘价上方 </body>
为您的所有页面添加标签。免责声明:这只是伪代码(未测试)。
<script>
document.addEventListener('DOMContentLoaded', function() {
if(typeof(Storage) !== 'undefined') {
// See if there is a scroll pos and go there.
var lastYPos = +localStorage.getItem('scrollYPos');
if (lastYPos) {
console.log('Setting scroll pos to:', lastYPos);
window.scrollTo(0, lastYPos);
}
// On navigating away first save the position.
var anchors = document.querySelectorAll('article a');
var onNavClick = function() {
console.log('Saving scroll pos to:', window.scrollY);
localStorage.setItem('scrollYPos', window.scrollY);
};
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener('click', onNavClick);
}
}
});
</script>
理论上这是做什么的:
“文档准备好后,检查浏览器是否支持 localStorage。如果支持,则检查是否设置了滚动位置。如果设置了,则滚动到该位置。”
“如果用户单击链接。将位置保存在存储中”
请注意,您甚至不知道下一页是否足够长。另请注意,这是不寻常且不明智的行为。
关于javascript - 使用 JavaScript 维护页面加载之间的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681718/