# 记录当前页面位置,返回 (龙泉司法项目)

需求: 从a页面进入b页面之后,然后返回a页面,要返回a页面固定的位置,

demo代码如下

龙泉司法案例图

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记录当前页面位置,返回</title>

    <style>
        .box {
            height: 3000px;
            background: yellowgreen;
        }

        button {
            position: fixed;
            top: 120px;
        }
    </style>
</head>

<body>

    <div class="box">
        asdkjfyasdf
    </div>

    <button class="buttonA">A按钮</button>



</body>

</html>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
<script>


    // 页面进入返回之前固定的位置
    function scrollToTop() {
        var aatop = localStorage.getItem('top')
        $(window).scrollTop(aatop);
    }
    scrollToTop()


    window.addEventListener('scroll', function () {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        console.log(scrollTop);

        localStorage.setItem('top', scrollTop)
    })

    $('.buttonA').on("click", function () {
        // var top = localStorage.getItem('top')
        // window.location.href = "bb.html?top=" + top;
        window.location.href = "bb.html" ;
    });




</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
上次更新: 7/11/2023, 15:32:07