2013-11-28 49 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