我正在尝试为我的网页制作一些过渡效果。
目标是在您第一次进入时淡入页面,然后当您单击链接时,该页面将淡出并淡化目标页面。但它不会获取目标网址,因此当我点击链接时,网址会更改为 www.example.com/#undefined
有什么建议吗?
jQuery.holdReady(true);
jQuery("body").css("opacity", 0);
jQuery.holdReady(false);
jQuery(function ($) {
$("body").fadeTo(1500, 1);
$(document).on("click", "a", function (event) {
event.preventDefault();
$("body").fadeTo(1500, 0, function () {
// get the href attribute
var newUrl = $(this).attr("href");
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page)
$("body").fadeTo(1500, 1, function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});
});
});
答案 0 :(得分:1)
在内部函数中,this
未指向被单击的<a>
元素。将newUrl
的分辨率移到该函数之外:
jQuery.holdReady(true);
jQuery("body").css("opacity", 0);
jQuery.holdReady(false);
jQuery(function ($) {
$("body").fadeTo(1500, 1);
$(document).on("click", "a", function (event) {
// get the href attribute
// "this" is still the <a> element here
var newUrl = $(this).attr("href");
event.preventDefault();
$("body").fadeTo(1500, 0, function () {
//here, where you were trying to get the url, "this"
//points to the animated element, ie body
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
//just update the location without fading in at this point
location = newUrl;
// prevent the default browser behavior.
return false;
});
});
});