将div放在textarea jquery中的文本下面

时间:2016-03-03 21:56:48

标签: javascript jquery

我需要将div放在textarea中的文本下面。所以,如果我在这里打字,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/

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

如果您希望在textarea文本下方显示div的固定高度,则可以执行此操作。

JS可扩展texarea取自@SpYk3HH's answer

我的小提琴: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中
相关问题