css - 文本开始溢出时如何使用动态替换文本?

标签 css html

如果我在页面加载时(但在设计时不知道)有三个文本字符串,例如:

  1. 全文可能有点长。
  2. 部分文字较短。
  3. 小文本。

我如何将文本放置在某些 HTML 元素(div 或 span 很好)中而不换行,例如当用户执行某些调整 HTML 元素大小的操作时,最长的文本是首选,但如果文本会溢出,切换到下一个不会溢出的最短文本?调整小于最小文本的大小将隐藏任何溢出(即 HTML 元素将溢出:隐藏)。

最佳答案

只要您愿意限制高度,您就可以使用 CSS 做到这一点。由于您只需要 1 行文本,因此将高度限制为 1em 似乎不是不合理的限制。

当你 float 一个元素时,当第一行没有足够的空间时,它会流动到下一行。此解决方案中的每一行都有两个元素:

  1. 一个宽度为 1px 的 breaker 元素。不幸的是,根据我的测试,这个元素必须有一定的宽度才能参与流程。
  2. 要显示的文本。

文本必须按从短到长的顺序排列,并且不得有透明背景。使用透明背景可以让较短的文本显示出来。

.container {
  white-space: nowrap;
  height: 1em; /* Must be fixed height */
  width: 100%; /* Or any width you want */
  overflow: hidden; /* Make sure that the elements that are bumped down don't show */
  border: 1px solid red; /* For example only */
}

.container p {
  position: relative; /* Relative to allow shifting elements up */
  float: left;
  left: 0;
  padding: 0;
  margin: 0;
  height: 1em; /* Text block must be fixed height */
  background-color: white; /* Text block must be opaque */
}

.container .break {
  float: left;
  clear: left;
  width: 1px;
  height: 1em; /* Must be the same height as a text block */
}

/* Shift each longer text block up to sit atop the first one */
.container p:nth-child(4) {
  top: -1em;
}
.container p:nth-child(6) {
  top: -2em;
}


/* Code below is just to animate the width for the sake of this example, and is not part of the solution */
@keyframes changewidth {
  from { width: 100%; }
  to { width: 1%; }
}

.container {
  animation-duration: 5s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
<div class="container">
  <div class="break"></div>
  <p>Short summary</p>
  <div class="break"></div>
  <p>This is a shorter version of the summary text.</p>
  <div class="break"></div>
  <p>This is a really long version of the summary text. I could go on forever. Isn't this great?</p>
</div>

关于css - 文本开始溢出时如何使用动态替换文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38247323/

相关文章:

html - 从中心开始的无限水平动画

javascript - 当取消第一个 Ajax 请求时,Bootstrap Alert Div 不会显示在第二个 ajax 请求上

javascript - 在 d3js styleTween 中使用 CSS calc 时发生意外转换

html - 同时在两个元素上设置 css3 动画

javascript - 为什么我将 JQuery/CSS 代码导入到我的 Wordpress 网站时它不起作用?

javascript - 单击链接时下拉菜单关闭

html - 如何自定义 bootstrap 默认顶部固定导航,如下图所示?

jquery - 滚动时更改 View 中特定 div 的背景颜色的最佳方法是什么?

Javascript:如何在网站上进行拖放操作时设置光标?

javascript - 关闭 Canvas 导航默认打开/关闭