0

亲爱的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>
4

1 回答 1

0

尝试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>   

这里纠正了两个主要问题:

  1. $(function() {...});将在 DOM 完全加载后触发 jQuery-Events
  2. var linkLocation必须在redirectPage()-Method中访问它们之前定义

为了消除错误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 测试的元素,例如您的<footer id='test'>.

于 2013-03-26T18:40:22.520 回答