将 div 放置在文本区域 jquery 中的文本下方



我需要将div放置在文本区域中的文本下方。因此,如果我在这里输入,div 应该在下面的行中,依此类推......

任何想法如何让这个文本位置将div 放在它下面?

我所做的只是获得div 位置,而不是文本。

var offset = $('#comment').offset();
var x_pos = offset.left;
var y_pos = offset.top;
  $("#display").css({
        top: x_pos,
        left: y_pos
  });

.html:

<textarea id=comment>how to position #display always below this text? (even if I press enter)</textarea>
<div id=display></div>

https://jsfiddle.net/krxz4ogg/

如果您在div 上有一个固定的高度,您希望显示在文本区域文本下方,则可以这样做。

JS可扩展的texarea取自@SpYk3HH的答案。

我的小提琴:https://jsfiddle.net/u2q3gw7x/

$("#MyExpandingTextArea").keyup(function(e) {
  //  this if statement checks to see if backspace or delete was pressed, if so, it resets the height of the box so it can be resized properly
  if (e.which == 8 || e.which == 46) {
    $(this).height(parseFloat($(this).css("min-height")) != 0 ? parseFloat($(this).css("min-height")) : parseFloat($(this).css("font-size")));
  }
  //  the following will help the text expand as typing takes place
  while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
    $(this).height($(this).height() + 1);
  };
});
#MyExpandingTextArea {
  padding-bottom: 6em;
  font-size: 1em;
  line-height: 1em;
}
#MovingDiv {
    border: 1px solid black;
    height: 3em;
    width: 3em;
    margin-top: -4em;
    margin-left: 10px;
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea name="myTextArea" id="MyExpandingTextArea"></textarea>
<div id="MovingDiv">
  &nbsp;
</div>

如果您不希望整个文本区域的效果扩展,请考虑将文本区域包装在具有固定高度和overflow: hidden;的div 中

您将无法检测到默认文本区域的文本底部 - 尝试对文本区域使用自动调整大小插件(类似这样),因此它具有文本的高度 - 可能是最简单的解决方案,因为您实际上不需要在此之后定位div - 它将始终在文本下方没有任何魔法。

最新更新