请参阅文本更改Div大小时

时间:2015-10-13 10:20:53

标签: javascript jquery html

我有一个div,一个内容的容器,可以改变大小以适应其中的文本。我希望div的大小保持不变。

我正在动态更改此内容,并且我希望能够知道文本何时太大而无法容纳在容器内,并且要删除使容器增长的文本部分。

这样的事情:

enter image description here

有可能吗?

4 个答案:

答案 0 :(得分:1)

我相信你不需要Javascript,但你可以用CSS解决它。给容器一个固定的高度并隐藏溢出:

div {
  line-height: 1em;
  height: 2em;
  width: 10em;
  border: 1px solid red;
  overflow: hidden;
  margin-bottom: 1em;
}
<div>
  bla bla bla<br />
  bla bla bla
</div>

<div>
  Oh no<br />
  The container changed
  its size to fix the text!
  I've got to get rid some
  of this annoying text
</div>

答案 1 :(得分:1)

使用Css text-overflow:

例如:

text-overflow: clip;会在容器端剪切单词

text-overflow: ellipsis;会在最后一个可见的字符后输入“...”。

HERE是一个不错的演示...

答案 2 :(得分:1)

没有大小改变的倾听者。您可以设置检查高度的间隔(例如下面的示例)。甚至更好:更新文本时执行检查!

&#13;
&#13;
setInterval(function() {
  if ($('#the-container').height() > 42) {
    // do something with container
  }
}, 50); // Can change time to whatever floats your boat
&#13;
&#13;
&#13;

代码没有经过测试,但我认为你明白了。

答案 3 :(得分:1)

是的,这是可能的。你可以修复div或容器的高度,并使overflow-y auto;

小提示演示:

&#13;
&#13;
.static{
    overflow-y:auto;
    height:100px;
    overflow-x:hidden;
    width:200px;
    border:1px solid red;
}
.right{float:right}
.left{float:left}
&#13;
<div class="static left">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>


<div class="static right">esse cillum dolore eu fugiat </div>
&#13;
&#13;
&#13;

https://jsfiddle.net/DhwaniSanghvi/31hryaw2/