2013-05-07 65 views
1

我期待添加滾動功能點擊事件。如果點擊按鈕向下滾動,然後向上滾動。jquery滾動到切換

到目前爲止,我有這個,但需要在click $('#review-link').click(function(e) { });

function scrollToAnchor(anchor){ 
    var aTag = $("#new_comment"); 
    $('html,body').animate({scrollTop: aTag.offset().top},'slow'); 
    } 

$("#review-link").click(function() { 
    scrollToAnchor('#new_comment'); 
}); 

感謝向上滾動。還有什麼方法可以避免在url中使用href =「#」?

+1

你可以將它張貼在的jsfiddle或交至少你的HTML代碼?謝謝。 – Madthew 2013-05-07 14:59:36

+0

這裏你去http://jsfiddle.net/qVGVR/ – olimart 2013-05-07 21:02:43

回答

2

我重拍的完整代碼,看看這裏

function scrollToAnchor(anchor){ 
    var aTag = $(anchor); 
    // you want to scroll to something that doesnt exist anymore when you 
    // toggle it out, makes no sense 
    // alert(aTag.offset().top); 
    $('html,body').animate({scrollTop: aTag.offset().top},'slow'); 
    } 

$('#review-link').click(function(e) { 
    $('.new_comment').toggle(); 
    // $('.comments').toggle(); 
    $(this).toggleClass('active'); 
    if($(this).hasClass('active')){ 

     $(this).text('Exit review mode'); 
     scrollToAnchor('.comments'); 
     return false; 

    }else{ 

     $(this).text('Enter review mode'); 
     $('body').animate({scrollTop: 0},'slow'); 
     return false; 
    } 
}); 

http://jsfiddle.net/tAQYf/2/

+0

謝謝,這是幫助。同時我更新了代碼。請看看http://jsfiddle.net/qVGVR/ – olimart 2013-05-07 21:03:16

+0

我不明白你想要滾動到哪裏?使更多的元素或許是一個例子.. – Johnny000 2013-05-07 22:25:37

+0

謝謝@ johnny000 - 在您的示例中,第一次滾動我想向下滾動到評論div。其他條件我希望它滾動到頂部 – olimart 2013-05-08 03:41:39