javascript - React - 根据宽度缩短字符串

标签 javascript css reactjs

我有一个宽度为500px的容器。 该容器中有 2 个字符串,“iiiiiiiiiiiiiii”和“MMMMMMMMMMMMMM”。您可以清楚地看到“M”字符串比“i”字符串宽很多,但两者都适合 500px 屏幕。 enter image description here

如果我将容器变小,假设 350px,M 字符串太宽,我想删除一些“M”,这样它就可以适合:

enter image description here

在 React 中我有以下数据:

var i = 'iiiiiiiiiiiiiii';
var M = 'MMMMMMMMMMMMMMM';
var containerWidth = 500;

根据什么信息来缩短字符串?

我从 if string.length > containerWidth/10 开始,但这不对,因为 string-length != width。我无法使用 getElementById 然后使用 .offsetWidth

最佳答案

您只能使用 css 来做到这一点:

.container {
  width: 350px;
  border: 2px solid black;
  padding: 20px;
  white-space: nowrap; 
  overflow: hidden;
  text-overflow: ellipsis;
}
<div class="container">
  IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
  MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
</div>

会导致这样的结果。运行实时演示的代码片段。

---------------------
| IIIIIIIIIIIIIIIIII|
| MMMMMMMMMMMMMMM...|
---------------------

关于javascript - React - 根据宽度缩短字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925081/

相关文章:

html - fieldset 没有完全显示在 div 周围

javascript - 如何在鼠标悬停时打开 react-bootstrap Dropdown?

html - 元素无意中随着内容的变化而移动

javascript - 有没有办法避免将所有参数传递给函数

javascript - 显示 ui-router 模式而不刷新父状态

javascript - 自定义 phong 着色器

javascript - 停止 Jest 对 TS 文件运行测试,并且仅对 JS 文件运行测试

javascript - 为 `<select>` s 的所选选项显示不同的文本

javascript - wow.js 发生在页面加载时而不是滚动时

javascript - 当没有任何 url queryString 参数时,React Router v6 重定向