【问题标题】:position div below text in textarea jquery在textarea jquery中将div放在文本下方
【发布时间】:2016-04-19 20:22:05
【问题描述】:

我需要将 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/

【问题讨论】:

  • 请包含相关的 html 本身。问题应该是自包含的,这样当前和未来的读者都可以在不离开网站的情况下查看您的问题
  • 你想要它在文本下方,在文本区域吗?还是完全低于整个文本区域?
  • @Chizzle 在文本区域中的文本下方,如果可能的话...
  • 需要将文本放入另一个容器并不断检查高度。建议查看文本区域的自动大小脚本,并在每次击键时设置另一个文本区域的值......然后根据该容器高度调整您的 div。或者自动调整你的 textarea 的大小并将 div 留在它下面

标签: javascript jquery


【解决方案1】:

如果你的 div 有一个固定的高度,你希望它出现在你的 textarea 文本下方,你可以这样做。

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>

如果不想要整个textarea展开的效果,可以考虑将textarea包裹在一个固定高度的div中,overflow: hidden;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多