2014-04-11 33 views
0

我有一個簡單的腳本,我用於選項卡式導航。它只是隱藏並顯示一個div。但是,當我從標籤頁更改爲標籤頁時,屏幕始終會回到頂部!任何人都知道如何解決這個問題?我的腳本如下:停止腳本從滾動返回頁首onclick

<script type="text/javascript"> 

$(document).ready(function() { 

    //Default Action 
    $(".tab_content").hide(); //Hide all content 
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab 
    $(".tab_content:first").show(); //Show first tab content 

    //On Click Event 
    $("ul.tabs li").click(function() { 
     $("ul.tabs li").removeClass("active"); //Remove any "active" class 
     $(this).addClass("active"); //Add "active" class to selected tab 
     $(".tab_content").hide(); //Hide all tab content 
     var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content 
     $(activeTab).fadeIn(); //Fade in the active content 
     return false; 
    }); 

}); 
</script> 
+0

顯示你的HTML請 –

+0

嘗試這樣:[平滑錨點] [1] [1]:http://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to- an-anchor – jbyrne2007

回答

0

我認爲你需要一個preventDefault()到你的點擊處理程序。

這將停止瀏覽器從平移到頂部。

像這樣:

//On Click Event 
$("ul.tabs li").click(function(e) { 
    e.preventDefault(); 
    $("ul.tabs li").removeClass("active"); //Remove any "active" class 
    $(this).addClass("active"); //Add "active" class to selected tab 
    $(".tab_content").hide(); //Hide all tab content 
    var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content 
    $(activeTab).fadeIn(); //Fade in the active content 
    return false; 
}); 
0

試着改變你的點擊處理程序爲目標的<a/>標籤,而不是<li/>標籤:

//On Click Event 
$('ul.tabs li a').click(function() { 
    $('ul.tabs li').removeClass('active'); 
    $(this).closest('li').addClass('active'); 
    $('.tab_content').hide(); 
    var activeTab = $(this).attr('href'); 
    $(activeTab).fadeIn(); 

    return false; // prevent default action of <a/> element 
}); 

出現這種情況的原因是,即使你正在返回在<li/>標記的點擊處理程序中爲false,<a/>標記的點擊事件冒泡,並且在其包含在<li/>標記中的同時被觸發。由於沒有點擊處理程序阻止</a>標記的默認操作,因此頁面跳轉到頂部 - 這是假設href屬性以散列開頭。

我希望這有助於!

+0

Didnt似乎工作,但我得到你的話,仍然無法解決跳躍。 – user2151867

+0

你能用相關的HTML標記更新你的問題嗎?另外,創建一個展示問題的JSFiddle將幫助我們確定解決方案。 – dSquared