亲爱的stackoverflowers鲜花
我有两个javascript代码片段,它们似乎不能在一起正常工作。第一个是在导航中的单击事件上淡出正文,然后重定向到不同的页面。但这似乎只有在我点击了一个触发“JavaScript-2”的链接后才能起作用。
下面是第一个的代码:
// JavaScript-1
<script type="text/javascript">
$("a.transition").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
function redirectPage() {
window.location = linkLocation;
}
</script> ‘’JavaScript 2‘是第二个,它与'jquery.easing.1.3.js’一起工作,并产生很好的平滑滚动到锚点。滚动总是工作得很好,它在所有情况下都会触发。
我不知道为什么,但看起来像是平滑滚动的javascript导致其他javascript失败。
我真的很期待这个小谜团的答案。
下面是第二个的代码:
// JavaScript-2
<script type="text/javascript">
$(function() {
$('ul.navscroll a, #test a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
</script>发布于 2013-03-27 02:40:23
尝试像这样更新您的Javascript-1代码:
// JavaScript-1
<script type="text/javascript">
$(function() { // this fires the jQuery after load
var linkLocation = false; // define the linkLocation var
$("a.transition").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
function redirectPage() {
window.location = linkLocation;
}
});
</script> 这里更正了两个主要的东西:
在DOM完全完成后,
$(function() {...});将触发jQuery事件。在redirectPage()-Method中访问事件之前,必须先定义loaded
var linkLocation为了消除Javascript-2中的错误(它破坏了Javascript),请像这样更新它们:
// JavaScript-2
<script type="text/javascript">
$(function() {
$('ul.navscroll a, #test a').bind('click',function(event){
target = $(this).attr('href'); // find the top of the target
offset = $(target).offset(); // this returns an object {top: y,left: x}
$('html, body').stop().animate({
scrollTop: offset.top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
</script>现在,如果您单击带有href='#test'的链接,您将滚动到ID为test的元素,例如您的<footer id='test'>。
https://stackoverflow.com/questions/15644701
复制相似问题