你需要做的是在你的
slideToggle
调用中添加一个“complete”参数。在其中,只需检查打开内容的高度,如果超出了视口的内部高度,则将视口滚动到内容的顶部。
这里是jsFiddle演示这个想法。
在那个例子中,我的视口是一个固定的最大高度div。我切换了一大块文本。在完成函数中,我检查文本的高度,如果必要,滚动父div。
这是相关的javascript:
$(document).ready(function(){
$('#toggler').on("click", function() {
$('#content').slideToggle("slow", function() {
if($(this).position().top + $(this).height() > $(this).parent().innerHeight()) {
$(this).parent().scrollTop($(this).position().top - 10);
}
});
});
});
请注意滚动位置中的额外-10
- 不知何故,在测试时它总是滚动超出div的起始位置10个像素,因此这是一个肮脏的hack,以滚动到正确的位置。
编辑:我稍微更新了javascript代码,使其将新打开的div定位在视口底部100像素处,而不是将其带到视口顶部。您可以使用-100
部分来修改定位。由于某种原因,我无法让jsfiddle保存我创建的内容并给我唯一的url - 那里有些东西没有正常工作,因此这是我的完整代码。
HTML:
<div class="viewport">
<button id="toggler">More info</button>
<img src="http://www.random.org/analysis/randbitmap-rdo-section.png" />
<div id="content">Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</div>
</div>
CSS:
.viewport {
max-height: 300px;
border: solid 1px darkGrey;
padding: 10px;
overflow: auto;
}
div#content {
display: none;
}
Javascript:
$(document).ready(function () {
$('#toggler').on("click", function () {
$('#content').slideToggle("slow", function () {
if ($(this).position().top + $(this).height() > $(this).parent().innerHeight()) {
$(this).parent().scrollTop($(this).position().top - $(this).parent().innerHeight() + 100)
}
});
});
});