2012-08-08 59 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