我想做什么:
在第A页上,有许多网页的链接,例如第B页,第C页等。
当我点击链接时,我希望当前页面淡出,新页面淡入。
我搜索了很多并获得了很多jquery解决方案 - 它们工作正常,但我想知道如何才能在vanilla javascript 中执行此操作。我试图自己解决这个问题,但它不起作用。我已经检查过控制台错误并将JS脚本放在页脚中。
document.addEventListener("click", "a", 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)
document.querySelector("html").fadeOut(function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});}
答案 0 :(得分:2)
在vanilla javascript中完成。
当您点击链接时,代码段会延迟下一页的默认加载,直到淡出动画完成为止。
document.querySelector("a").addEventListener("click", function () {
event.preventDefault();
// get the href attribute
var newUrl = this.getAttribute("href");
document.querySelector("body").addClass("fade-out");
// verify 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). You need to set the duration manually.
//if you have an animation that lasts .5, 1 or 2 seconds etc, you need to put the duration below
var animationDuration = 500;
setTimeout(function() {
location = newUrl;}, animationDuration);
});}
答案 1 :(得分:0)