我对 ajax 和历史状态很陌生。现在我正在做这个网站,我用pjax加载博客文章。像codrops 中等风格的过渡。因为我重新创建了相同的效果并且没有使用任何 codrop 的代码,所以我无法使用后退和前进按钮。或者,也许我设置的事件都错了。或者一般认为这一切都错了。
// Function to refresh the .current and .next elements
function refreshSelectors(){
$blogpost_current = $('.current');
$blogpost_next = $('.next');
};
$_(document).on("click", "*[data-pjax]", function(e) {
e.preventDefault();
// Get url
var href = $(this).attr('href');
// Fade out current post
$blogpost_current.addClass('fade-up-out');
// Get the difference in height between .next and top of window
var translateValue = $blogpost_next.get(0).getBoundingClientRect().top;
// Add easing class on .next to move it to the top.
$blogpost_next.addClass('easing-upward').css({"transform": "translate3d(0, -" + translateValue + "px, 0"});
// Remove .next class and set it as current
$blogpost_next.removeClass('next').addClass('current');
// After 450ms
setTimeout(function(){
// Remove old .current post
$blogpost_current.remove();
// Remove easing-upward class on .next
$blogpost_next.removeClass('easing-upward');
// Snap it in place
$blogpost_next.css({"transform": ""});
// Scroll to top
$body.scrollTop(0);
$html.scrollTop(0);
// Refersh selectorer
refreshSelectors();
// Create new .next section, to fill the ajax content into
$blogpost_current.after('<section class="page next"></section>')
// Refersh selectorer
refreshSelectors();
// Make the pjax call
$.pjax({url: href, container: $blogpost_next, fragment: ".next", timeout: 2000});
}, 450)
});
所以基本上,当前和下一个条目最初都加载到页面上。而且里面的内容.next
是隐藏的。并且仅在类更改为 时可见.current
。请注意,只有当动画完成时,新的.next
才会由 pjax 创建和填充。也许我应该改用其他事件?那里的计时器可能已经放在实际事件中,或者?
或者,也许让后退和前进按钮实际重新加载页面是最简单的。
$(document).on('pjax:popstate', function(event) {
location.reload();
});
最好的解决方案是什么?正确完成后是否由 pjax 处理?还是我必须听 popstate 事件才能获得正确的内容?并且可能以相反的方式对其进行动画处理?