如何记住页面的滚动位置

编程入门 行业动态 更新时间:2024-10-21 11:37:47
本文介绍了如何记住页面的滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将一些数据提交给我的数据库,然后重新加载用户刚刚访问的同一页面,我想知道是否有办法记住用户刚才的滚动位置?

解决方案

我意识到我错过了提交的重要部分,因此,我决定调整代码以将cookie存储在点击事件中,而不是原始方式在滚动的时候存储它。

下面是一个jQuery的方式:

jsfiddle (只需添加 / show 在url的末尾,如果你想在框架之外查看它)

非常重要的是,你需要 jquery cookie插件。

jQuery:

//当文档准备好时... $(document).ready(function(){ //如果cookie是设置,滚动到保存的位置($ .cookie(scroll)!== null){ $(document).scrollTop($ .cookie(scroll)); //当点击一个按钮时... $('#submit')。on(click,function(){ //设置一个包含滚动位置的cookie $ .cookie(scroll,$(document).scrollTop()); }); });

这里仍然是原始答案的代码:

jsfiddle

jQuery:

//当文档准备好时... $(document).ready(function(){ //如果设置了cookie,滚动到保存在cookie中的位置 if($ .cookie(scroll )!== null){ $(document).scrollTop($ .cookie(scroll)); } //当滚动发生时... 。 $(window).on(scroll,function(){ //设置一个包含滚动位置的cookie $ .cookie(scroll ,$(document).scrollTop()); }); });

@科迪的回答让我想起了一件重要的事情。

我只是让它检查并垂直滚动到位置。

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?

解决方案

I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.

Here's a jquery way of doing it:

jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )

Very importantly, you'll need the jquery cookie plugin.

jQuery:

// When document is ready... $(document).ready(function() { // If cookie is set, scroll to the position saved in the cookie. if ( $.cookie("scroll") !== null ) { $(document).scrollTop( $.cookie("scroll") ); } // When a button is clicked... $('#submit').on("click", function() { // Set a cookie that holds the scroll position. $.cookie("scroll", $(document).scrollTop() ); }); });

Here's still the code from the original answer:

jsfiddle

jQuery:

// When document is ready... $(document).ready(function() { // If cookie is set, scroll to the position saved in the cookie. if ( $.cookie("scroll") !== null ) { $(document).scrollTop( $.cookie("scroll") ); } // When scrolling happens.... $(window).on("scroll", function() { // Set a cookie that holds the scroll position. $.cookie("scroll", $(document).scrollTop() ); }); });

@Cody's answer reminded me of something important.

I only made it to check and scroll to the position vertically.

更多推荐

如何记住页面的滚动位置

本文发布于:2023-10-08 01:37:22,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   页面

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!