javascript - FadeIN FadeOUT 页面转换 javascript bug
问题描述
当我单击任何链接以将我带到新的 HTML 页面时,javascript 会将我路由到相同的 HTML 页面,而不是每个链接单独的 href。
这是我的代码
$(document).ready(function() {
$('body').css('display', 'none');
$('body').fadeIn(1000);
$('.link').click(function(event) {
event.preventDefault();
newLocation = $('.link a').attr("href");
$('body').fadeOut(1000, newpage);
});
function newpage() {
window.location = newLocation;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>
我的目标是加载页面 FadeIN 并在单击链接时 FadeOUT,我得到了我想要的效果,但我只是不确定链接的这个问题是什么 - 有人知道吗?
解决方案
正如@Taplar 所说,当您从链接中获取位置时href
,您没有得到正确的位置。您只需获取文档中的第一个链接并查看其href
属性。
您可以通过替换它来轻松解决这个问题(它会在文档中查找与link
该类具有祖先的所有锚元素,然后返回它找到的第一个元素):
newLocation = $('.link a').attr('href');
有了这个(它找到所有锚元素作为任何元素的子元素,点击处理程序注册被点击):
newLocation = $(event.currentTarget).find('a').attr('href');
您正在做的另一件事很棘手,但不一定会破坏任何东西,它依赖于在处理程序和函数newLocation
之间正确共享。相反,我建议您将参数显式传递给 newpage 以便它更可重用,并且您可以确定值的来源。click
newpage
你可以在下面看到这个工作。
$(document).ready(function() {
$('body').css('display', 'none');
$('body').fadeIn(1000);
$('.link').click(function(event) {
event.preventDefault();
newLocation = $(event.currentTarget).find('a').attr('href');
// Pass anonymous function to fadeOut that calls newpage with newLocation
$('body').fadeOut(1000, function () { newpage(newLocation); });
});
// newpage now accepts a parameter and uses it
function newpage(location) {
// Print to console so you can see what URL is getting used
// You'll always get 404 using StackOverflow's UI since they don't have the relevant pages
console.log(location);
window.location = location;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>
推荐阅读
- java - 在 JDBC 中关闭 ResultSet 后的内存/堆状态
- javascript - k-means 聚类算法收敛但不是使用 javascript 的稳定收敛
- controller - 如何通过控制器和路由类使用节点 js 进行 crud 操作
- html - 尽管相对和 z-indexes 没有显示伪“after”元素
- c++ - 如何替换二叉搜索树中的节点
- javascript - 更改页面 react/redux 时继续播放音频
- r - 使用 R 对数据帧中的数据进行子集化,以便数据对一个条件有效而对其余条件无效
- keras - Keras 如何真正通过 epoch 拟合模型
- javascript - Server Stats 代码将通道更新为未定义而不是成员总数
- class - PlantUML:如何控制同等级类的对齐?