2013-11-28 47 views
0

這無疑是非常基本的HTML,但我有一些錨標籤的問題。我有一個包含三個重疊選項卡的頁面。你點擊標籤,內容就會出現在前面。問題是頁面垂直向下移動,使頁面位於頁面的頂部(通常是一半)。Ahref鏈接/錨點垂直移動頁面preventDefault();

附加是我的腳本來執行該功能,以及一個版本的HTML關聯。

我想我需要使用preventDefault();某處,但不知道在哪裏。任何想法讚賞。

<!--Javascript function to brings tabs to the front--> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $("div.tab-headers>a").click(function() { 
     // Grab the href of the header 
     var _href = $(this).attr("href"); 

     // Remove the first character (i.e. the "#") 
     _href = _href.substring(1); 

     // show this tab 
     tabify(_href); 
    }); 
    tabify(); 
}); 
function tabify(_tab) { 
    // Hide all the tabs 
    $(".tab").hide(); 

    // If valid show tab, otherwise show the first one 
    if (_tab) { 
     $(".tab a[name=" + _tab + "]").parent().show(); 
    } else { 
     $(".tab").first().show(); 
    } 
} 
// On page load... 
$(document).ready(function() { 
    // Show our "default" tab. 
    // You may wish to grab the current hash value from the URL and display the appropriate one 
    // tabify(); 
}); 
</script> 

我的HTML是:

<div class="glossary"> 

    <div class="tab-headers"> 
    <a href="#tab1"></a> 
    <a href="#tab2"></a> 
    <a href="#tab3"></a> 
    </div> 

    <!--Tab 1-->  
    <div class="tab"> 
    <a name="tab1"></a> 
    contents 1 here 
    </div> 

    <!--Tab 2--> 
    <div class="tab"> 
    <a name="tab2"></a> 
    contents 2 here   
    </div> 

    <!--Tab 3--> 
    <div class="tab"> 
    <a name="tab3"></a> 
    contents 3 here   
    </div> 
</div> 
+0

_「我想我需要使用preventDefault();某處,但不知道在哪裏。「_ - 怎麼樣:在實際處理點擊的地方......? – CBroe

+0

是的,但我不希望它跳,但保留它的位置。 CBroe,很抱歉,我在哪裏說,我不明白。謝謝 – user2406993

回答

1

相信preventDefault()方法應該在這裏:功能後

$("div.tab-headers>a").click(function(e){ 
    e.preventDefault(); 
    .... 

注意添加的(E)。所以這會導致下面的代碼:

<!--Javascript function to brings tabs to the front--> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $("div.tab-headers>a").click(function (e) { 
     e.preventDefault(); // normal behavior is stopped 
     // Grab the href of the header 
     var _href = $(this).attr("href"); 

     // Remove the first character (i.e. the "#") 
     _href = _href.substring(1); 

     // show this tab 
     tabify(_href); 
    }); 
    tabify(); 
}); 
function tabify(_tab) { 
    // Hide all the tabs 
    $(".tab").hide(); 

    // If valid show tab, otherwise show the first one 
    if (_tab) { 
     $(".tab a[name=" + _tab + "]").parent().show(); 
    } else { 
     $(".tab").first().show(); 
    } 
} 
// On page load... 
$(document).ready(function() { 
    // Show our "default" tab. 
    // You may wish to grab the current hash value from the URL and display the appropriate one 
    // tabify(); 
}); 
</script> 
+0

完美 - 謝謝 – user2406993