popState和动画 - pjax

时间:2012-08-05 13:27:04

标签: pjax popstate

我有一个滑出屏幕的div,加载新内​​容并向后滑动。 我使用jquery pjax,那部分效果很好:

$('#menu a').on('click', function(event){

  event.preventDefault();

  var target = $(this).attr('href');

  $('li.current').removeClass("current");
  $(this).parent().addClass("current");

  $(content).transition({left:$(document).width()}, 900, 'out', function() {

    $.pjax({
      url: target,
      container: '#content',
      fragment: '#content',
      success: function(){
        $(content).transition({ left:'0px'}, 900, 'out');

        var contentHeight = $('#content').outerHeight(true)+258+$("#footer").outerHeight(true);

        if(contentHeight<parseInt($("body").css("min-height"))){
          contentHeight = "100%";
        }

        $(page).stop(true).animate({height:contentHeight}, 1000, "easeOutCubic");
      }
    });

  });

});

但如果使用浏览器后退/前进按钮,我不会让它工作。 我尝试了不同的东西。 在这里,我发现了一篇很好的文章,但我没有得到它:http://artfindertech.wordpress.com/tag/historyapi/

事情是,当您单击浏览器后退按钮时,div的内容会发生变化。 然后它滑出但不回来。 此外,网址会在一秒钟内更改为上一页,但会跳转到网站的主网址。 这是我对popState的试用:

$(window).on('pjax:popstate', function() {

  $(content).transition({left:$(document).width()}, 900, 'out', function() {

    $.pjax({
      container: '#content',
      fragment: '#content',
      success: function(){
        $(content).transition({ left:'0px'}, 900, 'out');

        var contentHeight = $('#content').outerHeight(true)+258+$("#footer").outerHeight(true);

        if(contentHeight<parseInt($("body").css("min-height"))){
          contentHeight = "100%";
        }

        $(page).stop(true).animate({height:contentHeight}, 2000, "easeOutCubic");
      }
    });

  });

});

1 个答案:

答案 0 :(得分:1)

我正在努力做同样的事情,即在动态上获得动画功能。我现在看到的方式是:

  1. 在菜单上单击调用一个函数,该函数将为内容添加动画并在容器中填充新内容 -
    function animation(PageTitle,PageLink,check) {
        //check if it is a call from menu and if it is than
        //on animation and ajax complete call
        if (check) {
            setHistory(PageTitle,PageLink); // separate function to call it indimpendently
        }
    }
    
  2. 如上所述,动画完成后调用一个关于window.history.pushState的函数,如果是来自菜单链接的调用 -
    function setHistory(PageTitle,PageLink) {
        window.history.pushState({'ptitle':PageTitle,'plink':PageLink}, PageTitle, PageLink);
    }
    
  3. 之后设置onpopstatee函数将函数调用为反向动画和ajax -
    window.onpopstate = function(event) {
        animation(event.state.ptitle,event.state.plink,false);
    }
    
  4. 我还没有测试过,但我现在正在实施它。如果它能够工作,我会更新这个......

    <强>更新

    正如我所假设的那样,只是为了更新它并告诉它它像魅力一样。还有一件事,可能与他有关......我想你必须在原始页面加载时调用 history.replacestate ,以便有可能返回原始页面相对变量和动画。