这是示例 html 代码
<div style="width:100px;height:100px">
12345 1234 1234 1234 123 12345 1234 1234 123 1234 12345
</div>
我想要这样的效果:
12345 1234 1234
1234 1234 123
12345 1234
1234 1234
123 1234
12345
或
12345
123 1234
1234 1234
12345 1234
1234 1234 123
12345 1234 1234
或
12345 1234 12345
1234 1234 235
12345 123 1234
1234 123 212
123 1234 12
1234 12345
我试过使用 text-align
但结果不是我的预期。
如何在不添加很多 <br>
的情况下实现这种效果?和 $nbsp
,或添加许多 <div style="margin...">
通过硬编码?
谢谢。
最佳答案
How can I do this effect without adding many of
<br>
and 
, or adding many of<div style="margin...">
by hard code?
你不能。心形、长颈鹿形等也是如此。DOM 元素几乎都是矩形的。
你必须做一些事情,比如使用 Javscript。您对要求(等宽字体、将单词放在一起等)的要求不是很具体,但这里有一个例子。
<div id="trapezoid" style="width:100px;height:100px"></div>
<script>
var data = '12345 1234 1234 1234 123 12345 1234 1234 123 1234 12345';
var lines = [];
data.split(' ').reduce(function(str, word, i, array) {
str += word;
if(lines.length === 0 || str.length > lines[lines.length-1].length || i === array.length - 1) {
lines.push(str);
return '';
}
return str;
}, '');
document.getElementById('trapezoid').innerHTML = lines.join('<br>');
</script>
关于javascript - 如何像梯形一样对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896107/