防止div溢出的优雅方式

时间:2017-06-16 21:28:25

标签: javascript html css

我有以下代码:

.wrapper {
  border-top: 2px solid #C0C0C0;
  border-bottom: 2px solid #C0C0C0;
  white-space: nowrap;
  text-align: left;
  width: 100%;
  height: 9vh;
  display: flex;
}

.leftDiv {
  height: 9vh;
  margin-left: 1vw;
  position: relative;
  width: 100%;
}

.top {
  margin-top: 2vh;
  font-size: 2.6vh;
  top: 0;
  position: absolute;
}

.bottom {
  font-size: 1.9vh;
  bottom: 0;
  position: absolute;
}

.rightDiv {
  background-color: red;
  width: 20%;
  height: 9vh;
  float: right;
  border-left: 2px silver solid;
}
<div class="wrapper">
  <div class="leftDiv">
    <p class="top"><b>this cannot overflow right div  txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt</b></p>
    <p class="bottom">txt</p>
  </div>
  <div class="rightDiv"></div>
</div>

的jsfiddle: https://jsfiddle.net/a4zuv1n5/

这是我想要做的: enter image description here

当leftDiv文本(顶级类)溢出rightDiv div时,就在此之前一点点, 我想要出现几个点并替换“txt”溢出。这些点应该可以通过javascript操作,我想稍后在javascript中附加一个事件。  我怎么做到这一点?可能吗?这里可能需要javascript。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

查看text-overflow: ellipsis

https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

编辑:更新答案。

好的,让我们从头开始吧。你的css到处都是。我已将此归结为此代码集https://codepen.io/anon/pen/BZpKOx

中的基础知识

HTML

<div class="wrapper">
    <div class="leftDiv"> 
        <p class="top">
          this cannot overflow right div  txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt this cannot overflow right div  txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt this cannot overflow right div  txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt txt
      </p>
      <p class="bottom">txt</p>
    </div>
    <div class="rightDiv">
      Stuff in the right
    </div>
</div>

CSS

.wrapper {
  outline: 1px solid #000;
  display: flex;
}
.leftDiv {
  flex-grow: 1;
  overflow: hidden;
}
.leftDiv .top {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.rightDiv {
  outline: 1px solid #cc0000;
  width: 20%;
}

要获得您提到的可点击效果,可以像创建一个绝对定位的元素(div或锚)一样简单,右边:0并垂直定位以覆盖省略号。

答案 1 :(得分:0)

overflow:hidden;text-overflow: ellipsis;应用于<p class="top">元素。

这是因为您想要溢出的文字<div class="leftDiv">的直接子项,但 是{{1}的直接子项元素。

在这个JSFiddle中看到这个:https://jsfiddle.net/a4zuv1n5/3/