2013-08-01 209 views
0

您好我已經寫了一些代碼,滾動頁面後,點擊一個元素,但在平滑滾動之前,跳轉到頁面的頂部。有人能解釋我做錯了什麼嗎?jQuery - 平滑滾動到div

這是腳本

$('a[href*="#"]').click(function(e){ 
     e.preventDefault(); 
    if($(this).attr('href') == '#') { 
     $('html, body').animate({ 
     scrollTop: $('body').offset().top 
     }, 1000); 
     window.location.hash = ''; 
    } else { 
     $('html, body').animate({ 
      scrollTop: $($.attr(this, 'href')).offset().top - $(this).height() 
     }, 1000); 
     window.location.hash = $(this).attr('href'); 
    } 
     return false; 
}); 

,並告訴我,我在哪裏可以學習JS :)請

+0

Go thro'以下鏈接爲學習和Masterin g JS :) http://stackoverflow.com/questions/2687566/learning-javascript-in-one-weekend http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript –

+0

將此行放入'window.location.hash ='''是什麼原因?你有沒有嘗試沒有這條線? – anu

+0

是的,我已經嘗試了很多配置,但它仍然「跳躍」在Firefox中 – arclite

回答

0

這是菜單的HTML

<div class="menu"> 
    <div class="top"> 
    <ul class="menu_list"> 
     <li><a href="#">Start</a></li> 
     <li><a href="#o_nas">About</a></li> 
     <li><a href="#services">Services</a></li> 
     <li><a href="#portfolio">Portfolio</a></li> 
     <li><a href="#contact">Contact</a></li> 
    </ul> 
    </div> 
</div> 

這是修改後的腳本的菜單

//menu smooth scroll to element 
    $('a[href^="#"]').on('click',function(e){ 
     $target = $(this).attr('href'); 
     e.preventDefault(); 
     $('.active').removeClass('active'); 
     $(this).addClass('active'); 
     if($(this).attr('href') == '#') { 

      $('html, body').stop().animate({ 
      scrollTop: $('body').offset().top 
      }, 1000, function(){location.hash = $target;}); 
     } else { 
      $('html, body').stop().animate({ 
       scrollTop: $($target).offset().top + 57 - $('.menu').height() 
//this is important to add + height of menu holder div in my case it's 57 this removes jump effect in firefox 
      }, 1000,function(){location.hash = $target}); 

     } 
     return false; 
    }); 

我已經解決了我的問題,這是它,上面的代碼完美的作品對我我把它放在這裏給像我這樣的其他程序員;),我們得到了網頁更改和平滑滾動效果的單頁網站:P

0

本教程和演示瞭如何實現這一目標。看看它。 http://css-tricks.com/snippets/jquery/smooth-scrolling/

+0

這不是我正在尋找我的腳本工程偉大的鉻,但在Firefox中它無法正常工作。網址正在改變,但在滾動後它跳轉到元素,點擊後跳轉到網站的頂部 – arclite