1

我正在使用我在 SO 其他地方找到的这段代码:

// 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() );

});

});

我有 cookie.js 文件,代码运行良好。但是,我想拥有它,以便此代码仅在提交执行......现在,它会在每次加载时移动到最后一个滚动位置,这不是我想要的。

显然我无法清除 cookie 上的 cookie $(document).ready,因为代码根本不会做任何事情,对吧?有任何想法吗?

编辑 -

尝试了这段代码,但没有骰子(现在它根本不起作用):

<script type="text/javascript">

$(document).ready(function() {
$(':submit').on("click", function() {

 $.cookie("scroll", $(document).scrollTop() );

     if ( $.cookie("scroll") !== null) {
         $(document).scrollTop( $.cookie("scroll") );
         $.cookie('scroll', null, { path: '/' });
     }
 });

});
</script>
4

1 回答 1

4

这对我正在做的事情有效:

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

// If scroll AND location cookie is set, and the location is the same
//scroll to the position saved in the scroll cookie.
if ( $.cookie("scroll") !== null && $.cookie("location") !== null 
           && $.cookie("location") == $(location).attr('href')) {
    $(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() );

// set a cookie that holds the current location.
$.cookie("location", $(location).attr('href'));


});

});
</script>
于 2013-09-21T00:56:49.040 回答