我将一些数据提交给我的数据库,然后重新加载用户刚刚访问的同一页面,我想知道是否有办法记住用户刚才的滚动位置?
解决方案我意识到我错过了提交的重要部分,因此,我决定调整代码以将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.
更多推荐
如何记住页面的滚动位置
发布评论