Ahref链接/锚点垂直向下移动页面preventDefault();

时间:2013-11-28 12:43:57

标签: html anchor

这无疑是非常基本的HTML,但我有一些锚标签的问题。我有一个页面有三个重叠的标签。单击选项卡,内容将显示在前面。问题是页面垂直向下移动,因此选项卡位于页面顶部(通常是一半)。

附件是我执行该功能的脚本,以及相关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>

1 个答案:

答案 0 :(得分: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>