You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML页面关闭重开后恢复浏览位置的实现方案咨询

Hey there! Since you're just starting out with HTML and JavaScript, I'll break this down into a simple, easy-to-implement solution using basic browser features you can grasp right away.

How it works

We’ll use localStorage—a built-in browser tool that saves small data snippets locally on the user’s device—to store the last scroll position. When the page reopens, we’ll read that saved data and scroll the page back to where you left off.

Full Code (replace your existing code with this)

<html>
<head>
    <script>
        // Restore scroll position when the page finishes loading
        window.addEventListener('load', function() {
            // Fetch the saved position from localStorage
            const savedScroll = localStorage.getItem('lastScrollPosition');
            if (savedScroll) {
                // Scroll to the saved vertical position (0 = horizontal, no need for that here)
                window.scrollTo(0, Number(savedScroll));
            }
        });

        // Save current scroll position right before the page closes/refreshes
        window.addEventListener('beforeunload', function() {
            // Get how far down the page you've scrolled
            const currentScroll = window.scrollY;
            // Store that value in localStorage
            localStorage.setItem('lastScrollPosition', currentScroll);
        });
    </script>
</head>
<body>
    <!-- Added extra line breaks to make the page scrollable for testing -->
    uette like a man’s face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised.
    
    <br><br><br><br><br><br><br><br><br><br>
    More content here to make the page long enough to scroll...
    
    <br><br><br><br><br><br><br><br><br><br>
    Bottom of the page—scroll here, close the tab, then reopen to test!
</body>
</html>

Quick breakdown of key parts

  • window.scrollY: This gives us the number of pixels you’ve scrolled down from the top of the page.
  • localStorage.getItem() / localStorage.setItem(): Simple methods to read and write data to the browser’s local storage. The data stays even after the browser is closed.
  • load event: We wait for the page to fully load before scrolling, ensuring all content is rendered so the scroll position is accurate.
  • beforeunload event: This triggers right before the page closes or refreshes, so we save the scroll position at the last possible moment.

Testing tip

Make sure your page has enough content to scroll! I added extra <br> tags in the example so you can easily test the feature. If your real page is short, add more content or adjust element heights to make it scrollable.

内容的提问来源于stack exchange,提问作者David Beckam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:03