简体   繁体   English

如何记住滚动 position 并向后滚动

[英]How to remember scroll position and scroll back

I am using html2canvas library and when I call html2canvas.Parse() the page scroll to top.我正在使用 html2canvas 库,当我调用 html2canvas.Parse() 时,页面滚动到顶部。

I thought if i can remember the position before calling html2canvas.Parse(), so then i can go back to original scroll position.我想如果我能在调用 html2canvas.Parse() 之前记住 position,那么我可以 go 回到原始滚动 position。

  1. get the current position of browser scroll (specially vertical)?获取浏览器滚动(特别是垂直)的当前 position?
  2. scroll back to position which i stored earlier?滚动回我之前存储的 position?

I went for the modern html5 browser way of handling this.我选择了现代 html5 浏览器来处理这个问题。 it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.它将最后一个滚动位置存储在客户端 Web 浏览器本身中,然后在重新加载页面时将设置从浏览器读取回最后一个滚动位置。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {

    if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
        $(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
    }

    $(window).on("scroll", function() {
        localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
    });

  });
</script>
  1. Save scroll position to a variable将滚动位置保存到变量
  2. Do something做点什么
  3. Scroll Back向后滚动

I'm using jQuery in the example below to make things easy but you could easily do the same thing in vanilla js.我在下面的例子中使用 jQuery 来简化事情,但你可以很容易地在 vanilla js 中做同样的事情。

 var scrollPos; $('.button').on('click', function() { // save scroll position to a variable scrollPos = $(window).scrollTop(); // do something $('html, body').animate({ scrollTop: $("#cats").offset().top }, 500); // scroll back setTimeout( function() { $('html, body').animate({ scrollTop: scrollPos }, 500); }, 1000); });
 .button { position: fixed; font-size: 12px; margin: 10px; } #rainbow { height: 2000px; background: -webkit-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: -o-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: -moz-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: linear-gradient(red, orange, yellow, green, cyan, blue, violet); } #cats { width: 100%; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <input class="button" value="Scroll down a bit then click here for 1 second of cats!" type="button"> <div id="rainbow"></div> <img id="cats" title="By Alvesgaspar [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0 )], via Wikimedia Commons" width="1024" alt="Cat poster 1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Cat_poster_1.jpg/1024px-Cat_poster_1.jpg">

To Remember Scroll use this code要记住滚动使用此代码

$(document).ready(function (e) {
    let UrlsObj = localStorage.getItem('rememberScroll');
    let ParseUrlsObj = JSON.parse(UrlsObj);
    let windowUrl = window.location.href;

    if (ParseUrlsObj == null) {
        return false;
    }

    ParseUrlsObj.forEach(function (el) {
        if (el.url === windowUrl) {
            let getPos = el.scroll;
            $(window).scrollTop(getPos);
        }
    });

});

function RememberScrollPage(scrollPos) {

    let UrlsObj = localStorage.getItem('rememberScroll');
    let urlsArr = JSON.parse(UrlsObj);

    if (urlsArr == null) {
        urlsArr = [];
    }

    if (urlsArr.length == 0) {
        urlsArr = [];
    }

    let urlWindow = window.location.href;
    let urlScroll = scrollPos;
    let urlObj = {url: urlWindow, scroll: scrollPos};
    let matchedUrl = false;
    let matchedIndex = 0;

    if (urlsArr.length != 0) {
        urlsArr.forEach(function (el, index) {

            if (el.url === urlWindow) {
                matchedUrl = true;
                matchedIndex = index;
            }

        });

        if (matchedUrl === true) {
            urlsArr[matchedIndex].scroll = urlScroll;
        } else {
            urlsArr.push(urlObj);
        }


    } else {
        urlsArr.push(urlObj);
    }

    localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));

}

$(window).scroll(function (event) {
    let topScroll = $(window).scrollTop();
    console.log('Scrolling', topScroll);
    RememberScrollPage(topScroll);
});

This worked for me:这对我有用:

window.onbeforeunload = function () {
        var scrollPos;
        if (typeof window.pageYOffset != 'undefined') {
            scrollPos = window.pageYOffset;
        }
        else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
            scrollPos = document.documentElement.scrollTop;
        }
        else if (typeof document.body != 'undefined') {
            scrollPos = document.body.scrollTop;
        }
        document.cookie = "scrollTop=" + scrollPos + "URL=" + window.location.href;
    }

window.onload = function () {
    if (document.cookie.includes(window.location.href)) {
        if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) {
            var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/);
            document.documentElement.scrollTop = parseInt(arr[1]);
            document.body.scrollTop = parseInt(arr[1]);
        }
    }
}

Most of this code I found elsewhere, unfortunately I cannot find the source anymore.我在其他地方找到的大部分代码,不幸的是我再也找不到源代码了。 Just added a check to see if the URL is the same so that the scroll position is only saved for the same page, not for other pages.刚刚添加了一个检查以查看 URL 是否相同,以便仅保存同一页面的滚动位置,而不保存其他页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM