2012-08-08 53 views
0

我正在使用jquerys slideToggle方法,並希望添加一個回調函數,該滾動頁面也向下滾動,這樣即使新顯示的文本在頁面當前可見區域出現時也是可見的。scrollTop滑動後不工作切換

我發現了幾個similiar /相同的問題,但我不能得到任何的解決方案的工作,我是新來的JavaScript,所以我可以真的有人做到take a quick look at my code.

的Javascript

$(document).ready(function() { 

    //br is the most efficient way to get desired effect with inline h3's 
    $("<br/>").insertBefore("h3"); 

    //collapse all expandable sections on page load 
    $(".expansion_text").slideToggle("slow"); 
}); 

//Click for expansion 
$(function(){ 
    $("h3").click(function(){ 
     $(this).siblings(".expansion_text").slideToggle("slow", function(){ 
      if ($(this).is(":visible")){ 
       $("html, body").animate({ 
       scrollTop: $(this).offset().top 
       }, "slow"); 
      } 
     }); 

    }); 
});​ 

HTML

<div class="expandable"> 
<h3>The Prisoner of Benda</h3> 
<div class="expansion_text"> 
<p>Bender, I didn't know you liked cooking. That's so cute. The key to victory is discipline, and that means a well made bed. You will practice until you can make your bed in your sleep. This is the worst part. The calm before the battle. Bender! Ship! Stop bickering or I'm going to come back there and change your opinions manually!</p> 
</div></div> 
<div class="expandable"> 
<h3>Where the Buggalo Roam</h3> 
<div class="expansion_text"> 
<p>Are you crazy? I can't swallow that. Bender, quit destroying the universe! Belligerent and numerous. Can I use the gun?</p> 
<ol> 
<li>Can we have Bender Burgers again?</li> 
<li>I was all of history's great robot actors - Acting Unit 0.8; Thespomat; David Duchovny!</li> 
<li>I videotape every customer that comes in here, so that I may blackmail them later.</li> 
</ol> 
</div></div> 

編輯:SOLUTION,與接受的答案的幫助下達到,但我認爲足夠的不同,張貼在這裏以供將來參考:

//Click for expansion 
$(function(){ 
    $("h3").click(function(){ 
     toggleExpansion($(this).siblings(".expansion_text")); 
    }); 
}); 

function toggleExpansion(expandableText){ 
    expandableText.slideToggle("slow", function(){ 
      if ($(this).is(":visible")){ 

       var page = $("#page"); 

       page.animate({scrollTop: page.scrollTop() + 
        $(this).siblings("h3").position().top},1000); 

      } 

     }); 
} 

回答

1

AFAIK並非如此簡單。最近我遇到了類似的問題,發現nice solution here。它使用一個額外的但很小的jQuery resize plugin(1KB)。在這裏跟隨你的代碼的可能修改:

HTML:

<script type="text/javascript" src="http://github.com/cowboy/jquery-resize/raw/v1.1/jquery.ba-resize.min.js"></script> 

的Javascript:

$(".expansion_text").css('display','none'); //instead of .slideToggle("slow"); 

$.resize.delay = 10; 
$('.expandable').resize(function(){ 
    var page = $('#page'); 
    page.scrollTop(page.scrollTop() + $(this).children('h3:first').position().top); 
}); 

The fiddle is here.

+0

謝謝!我的解決方案實際上與您發佈的內容有點不同。我不需要該插件,即使jsfiddle足夠流暢,但仍需要使用動畫使其在實際網站上平滑流暢,但缺少的關鍵是使用了頁面。我曾嘗試之前,但由於某種原因,你使用它的方式讓東西移動:)你回答了這個問題,並花時間提供一個工作jsfiddle,所以我一定會標記你正確,但我也會包括我的完成在未來的任何人的原始問題的解決方案。 – Holly 2012-08-09 12:32:33