创建子div时,始终将div容器滚动到底部

问题描述 投票:3回答:1

首先这些是我的参考

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。然后逻辑将中断,容器不再滚动。

容器应滚动到当前div,编号为i(当前索引)

javascript jquery html css
1个回答
2
投票

仅仅因为高度总是固定的,而是考虑使用所有子元素的高度滚动,包括它们的上/下边距。换句话说,如果没有指定固定高度,则容器的高度。

更准确地说,您只需要滚动所有子元素的高度减去容器的固定高度,这是溢出的部分。这就是为什么你的代码部分工作,因为直到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>
© www.soinside.com 2019 - 2024. All rights reserved.