我想要一个带有垂直滚动条的容器来强制元素到页面顶部,即使它位于容器的底部。这最好通过这个jsfiddle来描述:
http://jsfiddle.net/scientiffic/v7CBu/5/
我有一个包含不同元素的可滚动容器(“容器”)。我可以单击页面上的链接以强制容器滚动到容器中的不同元素。但是,由于子容器“3”位于容器的底部,因此容器无法滚动,因此页面顶部会显示3。我想强制子容器3在顶部。这样做的最佳方式是什么?
HTML:
<div class="container">
<div class="subcontainer 1"><h1>1</h1></div>
<div class="subcontainer 2"><h1>2</h1></div>
<div class="subcontainer 3"><h1>3</h1></div>
</div>
<div class="controllers">
<div class="controller" id="1">jump to 1</div>
<div class="controller" id="2">jump to 2</div>
<div class="controller" id="3">jump to 3</div>
</div>
使用Javascript:
$(document).ready(function(){
$('#1').click(function(){
$('.container').animate({
scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
}, 500);
});
$('#2').click(function(){
console.log('go to 2');
$('.container').animate({
scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
}, 500);
});
$('#3').click(function(){
console.log('go to 3');
$('.container').animate({
scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
}, 500);
});
});
答案 0 :(得分:1)
您可以在下方添加垫片,并根据所点击的内容更改其高度。有点黑客,但它确实有效:
HTML:
<div class="container">
<div class="subcontainer 1">
<h1>1</h1>
</div>
<div class="subcontainer 2">
<h1>2</h1>
</div>
<div class="subcontainer 3">
<h1>3</h1>
</div>
<div class="shim"></div>
</div>
<div class="controllers">
<div class="controller" id="1">go to 1</div>
<div class="controller" id="2">go to 2</div>
<div class="controller" id="3">go to 3</div>
</div>
JS:
$(document).ready(function () {
$('#1').click(function () {
$('.shim').height(0);
$('.container').animate({
scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
}, 1000);
});
$('#2').click(function () {
console.log('go to 2');
$('.shim').height(0);
$('.container').animate({
scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
}, 1000);
});
$('#3').click(function () {
console.log('go to 3');
var newHeight = $('.container').height() - $('.subcontainer.3').outerHeight();
$('.shim').height(newHeight);
$('.container').animate({
scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
}, 1000);
});
});