我有一个宽度为500px的容器。 该容器中有 2 个字符串,“iiiiiiiiiiiiiii”和“MMMMMMMMMMMMMM”。您可以清楚地看到“M”字符串比“i”字符串宽很多,但两者都适合 500px 屏幕。
如果我将容器变小,假设 350px,M 字符串太宽,我想删除一些“M”,这样它就可以适合:
在 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/