2013-10-23 37 views
0

我對我的問題和答案頁面使用了點擊/隱藏功能。但是當我點擊問題來顯示答案時,它會跳回頂部。我需要做些什麼才能停止。jQuery中的顯示/隱藏功能問題。跳轉到頁面頂部

這是我的編碼:

腳本:

<script type="text/javascript"> 
jQuery(document).ready(function() { 
jQuery(".sub").hide(); 
//toggle the componenet with class msg_body 
jQuery(".cthrough").click(function() 
{ 
jQuery(this).next(".sub").slideToggle(500); 
});}); 
</script> 

CSS:

.cthrough { 
    display: inline-block; 
    font-size: 15px; 
    font-family: 'Anaheim', sans-serif; 
    text-transform: uppercase; 
    letter-spacing: 0px; 
} 

.sub { 
    display: inline-block; 
    font-size: 13px; 
    padding-left: 10px; 
} 

HTML:

<a href="#" class="cthrough">This is my question</a> 
<div class="sub"> 
    This is my answer. 
</div> 

我試圖在href =#轉換爲只是一個div類,但那個doe不要讓問題點擊。我也嘗試過#但沒有幫助。

+0

沒有重複,但相關的話題:http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links -or-javascriptvoid0/138233#138233 –

回答

3

保留您的href="#"並使用jQuery's .preventDefault()來防止跳回到頂部的默認操作。

jQuery(".cthrough").click(function(e) { 
    e.preventDefault(); // <-- first line 
    jQuery(this).next(".sub").slideToggle(500); 
    ... 
+0

謝謝。這很好。 –

+0

@Tessa,不客氣。請「接受」我的回答。 – Sparky

+2

謝謝,它效果很好!泰莎王爾德,請給予斯帕克他的回答! – John

0

遇到同樣的問題和e.preventDefault()不適用於我,如果我申請持續時間來說一個slideDown()。

一種哈克,但這對我很有用。 瀏覽器在試圖確定動畫過程中顯示的元素的大小時非常尷尬。因此,我馬上展示它,現在瀏覽器知道它的大小。 但是,低透明度,然後我剛剛褪去它

// show/hide jobs section 
$('.job').hide(); 

$('a.jobTrigger').click(function(e){ 
    $('.job').hide(); 
    $(this).next('.job').show(0, function() { 

     //animation to stop page jump 
     $(this).css('opacity' , '.1'); 
     $(this).animate({ 
      opacity: 1 
     }); 
    }); 
    e.preventDefault(); //keeps hash out of URL 
});