2 Javascript不能相互配合...(平滑滚动和淡入淡出正文)



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

尝试像这样更新您的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
  3. 中访问它们之前定义。

要删除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'>

最新更新