1. 立即淡出射击!
当您单击锚点时,下一页将开始加载,并且当前页面上的任何代码都将停止。您错误地涵盖了这种情况not等待fadeOut
完成!您需要将该调用包装在匿名函数中,
e.g.
$("body").fadeOut(1000, function(){redirectPage(linkLocation)});
否则你只是打电话redirectPage
立即地并将其返回值传递给 fadeOut 方法!
Option:另一种转换方法是使用 Ajax 加载所有页面。然后您可以应用任何您想要的效果(您通常可以在锚点单击事件处理程序中执行此操作)。这需要您在页面更改时更新浏览器历史记录,但非常有效(您可以通过任何方式转换页面)。
2.ajax加载:
您可以执行以下操作来替换整个页面:
JSFiddle:http://jsfiddle.net/TrueBlueAussie/bwdwc/3/ http://jsfiddle.net/TrueBlueAussie/bwdwc/3/
jQuery(function ($) {
$('.ghostly').animate({
opacity: '1'
}, 3000);
$(document).on('click', "a", function (event) {
event.preventDefault();
$.when($("body").fadeOut(4000).promise(), $.ajax({
url: this.href,
type: 'get',
dataType: 'html'
})).done(function (html) {
var newDoc = document.open("text/html", "replace");
newDoc.write(html);
newDoc.close();
$("body").css({
display: "none"
});
$("body").fadeIn(4000);
});
});
});
It uses $.when()
将动画承诺和 Ajax 调用结合起来。当两者都完成时,它会处理来自 Ajax 页面加载的数据并替换整个页面主体。
*Note: 由于“Access-Control-Allow-Origin”错误,这不会加载链接中的页面,但在您自己的网站中应该可以正常工作。
3.将大部分jQuery代码放入文件准备好:
任何访问“的 jQuery 代码existing“ 元素需要进入文档准备就绪(即您假设已经加载的元素。在这种情况下'a'
= 所有锚点).
e.g.
$(document).ready(function() {
$('.ghostly').animate({
opacity: '1'
}, 3000);
$("a").click(function(event) {
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage(linkLocation));
});
});
您可以将 jQuery 代码放在末尾body
以获得类似的效果,但它会导致代码的可移植性较差(特别是当代码位于单独的 .js 文件中时......它通常会/应该改进缓存)。
4. 或者使用延迟事件处理程序:
如果您使用延迟事件处理程序,您可以这样做:
<script>
$(document).ready(function() {
$('.ghostly').animate({
opacity: '1'
}, 3000);
});
// Catch all anchor clicks bubbled to the document...
$(document).on('click', "a", function(event) {
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage(linkLocation));
});
function redirectPage(link) {
document.location.href = link;
}
</script>
延迟事件处理程序通过侦听未更改的祖先元素处的事件来工作(例如,本例中的文档,因为它已经存在),then使用 jQuery 选择器来匹配元素,then为任何匹配元素调用该函数导致该事件的.
5、注意事项:
我还建议您使用此快捷方式来准备文档:
$(function(){
// Your code here
});
或者更好(以避免与 $ 命名空间冲突):
jQuery(function($){
// Your code using the local $ here
});
第二个版本是最好的包罗万象的版本,因为本文档准备传递对 jQuery 的引用作为第一个参数。注意:虽然它看起来很相似,但这不是您有时看到的包装 jQuery 代码的 IIFE(立即调用函数表达式).
6.最终推荐:
把所有这些放在一起,你会得到这个:
jQuery(function($) {
$('.ghostly').animate({
opacity: '1'
}, 3000);
$(document).on('click', "a", function(event) {
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, function(){redirectPage(linkLocation)});
});
});