您好,谢谢您提供任何解决方案。我一直在尝试在用户切换页面时添加淡入和淡出功能。我尝试了在这里和其他论坛上找到的许多解决方案,但似乎都无法解决。淡入效果很好,我只需要在body标签上添加.ghoSTLy即可。我所做的一切都对淡出没有作用。任何帮助将不胜感激,因为我是编码的新手。
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.ghostly {
opacity: 0;
}
</style>
<script>
$(document).ready(function() {
$('.ghostly').animate({
opacity: '1'
}, 3000);
});
$("a").click(function(event) {
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage(linkLocation));
});
function redirectPage(link) {
document.location.href = link;
}
</script>
最佳答案
1.淡出立即射击!
当您单击 anchor 时,下一页将开始加载,当前页上的所有代码都将停止。您通过而不是来等待fadeOut
完成而错误地解决了这种情况!您需要将该调用包装在匿名函数中,
例如
$("body").fadeOut(1000, function(){redirectPage(linkLocation)});
否则,您只是立即调用
redirectPage
并将其返回值传递给fadeOut方法!选项:另一种转换方法是使用Ajax加载所有页面。然后,您可以应用所需的任何效果(可以在定位点击事件处理程序中进行常规操作)。这需要您在页面更改时更新浏览器历史记录,但是非常有效(您可以通过任何方式转换页面)。
2. Ajax加载:
您可以执行以下操作来替换整个页面:
JSFiddle: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);
});
});
});
它使用
$.when()
组合动画 promise 和Ajax调用。当两者都完成时,它将处理Ajax页面加载中的数据,并替换页面的整个正文。*注意:由于出现“访问控制允许来源”错误,因此该页面不会加载链接中的页面,但在您自己的网站上应该可以正常工作。
3.准备好大多数jQuery代码到文档中:
任何访问“现有”元素的jQuery代码都需要进入文档准备就绪(即您假设已加载的元素。在这种情况下,
'a'
=所有 anchor )。例如
$(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>
延迟事件处理程序的工作方式是侦听未更改的祖先元素上的事件(例如,在本例中为文档,因为它已经存在),然后使用jQuery选择器来匹配元素,然后对导致该元素的任何匹配元素调用该函数事件。
5.注意事项:
我也建议您始终使用此快捷方式来准备文档:
$(function(){
// Your code here
});
或更好的方法(以避免 namespace 与$冲突):
jQuery(function($){
// Your code using the local $ here
});
第二版是最好的工具,因为本文档准备将对jQuery的引用作为第一个参数传递。注意:尽管它看起来很相似,但它不是IIFE(立即调用的函数表达式),您有时会看到它包装了jQuery代码。
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)});
});
});