javascript - 如何在 JavaScript 中对齐文本

标签 javascript jquery html

我的数组中有很多字符串

const arr = ["Hello my name is jimmy", "will you go to the cinema with me?", "who's him?"]

我想从数组中检索字符串并将其放在我的列表中,所以我首先循环它,但我想让文本对齐,因为我已经设置了列表的最大宽度例如:100px

<span style="width: 100px" id="hello">
</span>

arr.forEach(e => {
   const str1 = e.substr(0,10)
   const str2 = e.substr(10) 
   $('#hello').append(str1 + '\n' + str2 + '\n')
})

我从这段代码得到的结果是

Hello my n
ame is jimmy
will you g
o to the cinema with me?
who's him?
(white space)

但我希望得到这样的结果:

Hello my
name is jimmy
will you 
go to the cinema with me?
who's him?
(white space)

如何使其动态化? (非静态)

最佳答案

您可以尝试如下

var arr = ["Hello my name is jimmy", "will you go to the cinema with me?", "who's him?"]
arr.forEach(e => {
   $('#hello').append(e+" ")
})
#hello{
  display:block;
  width:100px;
  text-align:justify;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="width: 100px" id="hello">
</span>

关于javascript - 如何在 JavaScript 中对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48780236/

相关文章:

javascript - 打印时绝对定位元素的位置不正确

javascript - 基于点击按钮的动态 URL

html - 响应式网站内容

css - 如何在 wordpress 中分离两个包含堆叠在每个上方的图像的 div?

javascript - 计算一个字符串有多少个子串是回文

javascript - 服务器端页面加载之前的 Vb asp.net JavaScript?

javascript - div 窗口应该在顶部

javascript - javascript普通变量和带美元符号的变量的区别

javascript - 获取 CSS 值并将其更新为 SQL

javascript - jQuery 从左滑动 + 昏暗的背景