首先,这些是我的推荐信
jQuery Scroll to bottom of page/iframe
jQuery Scroll To bottom of the page
我创建了一些div并将它们放入div容器中。我希望容器始终滚动到底部最新的div。
$(document).ready(function() {
var container = $("#container");
var i = 0;
$("#btn").click(function() {
i++;
var div = $("<div></div>");
div.addClass("d");
div.html("Container " + i);
container.append(div);
container.scrollTop(container.height());
});
});
body {
background: white;
}
#container {
height: 160px;
width: 120px;
overflow-y: scroll;
background: gray;
}
.d {
height: 30px;
margin-bottom: 10px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">-- Add --</button>
<div id="container">
</div>
如您所见,在我创建超过8个div之前,这是很好的工作方式。然后逻辑将中断,容器不再滚动。
容器应该使用数字i(当前索引)滚动到当前div。
发布于 2018-03-01 11:39:27
因为高度总是固定的,所以考虑使用all的高度滚动子元素,包括它们的上/下边缘。换句话说,如果没有指定的固定高度,则为容器的高度。
更准确地说,您只需要滚动所有子元素的高度减去容器的固定高度,即溢出部分。这就是为什么您的代码部分地工作,因为直到有8个元素的溢出低于容器的固定高度( 8 * 40 = 320
=> 320 - 160(fixed height) = 160(overflow)
)。
$(document).ready(function() {
var container = $("#container");
var i = 0;
$("#btn").click(function() {
i++;
var div = $("<div></div>");
div.addClass("d");
div.html("Container " + i);
container.append(div);
container.scrollTop(container.find('.d').length *
($('.d').height() + 10) -
container.height());
});
});
body {
background: white;
}
#container {
height: 160px;
width: 120px;
overflow-y: scroll;
background: gray;
}
.d {
height: 30px;
margin-bottom: 10px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">-- Add --</button>
<div id="container">
</div>
https://stackoverflow.com/questions/49048643
复制相似问题