Javascript 函数根据新行向 <p> 标签添加边距

时间:2021-06-28 19:43:46

标签: javascript

我在 javascript 上有一个带有新行的文本。我使用 text.split('\n') 将其拆分为一个数组。

所以我现在拥有的是:

[
  'Hello world',
  '',
  '',
  'This is the first line',
  '',
  'This is the second line',
  '',
  '',
  '',
  '',
  'This is the last line'
]

我希望每个新行的边距为 5px,所以我想将其转换为:

<p style={{ marginBottom: '10px' }}>Hello world</p>
<p style={{ marginBottom: '5px' }}>This is the first line</p>
<p style={{ marginBottom: '20px' }}>This is the second line</p>
<p>This is the last line</p>

我想我可以写一个函数来做到这一点:

  1. 在 0 处启动一个累加器。
  2. 从上到下循环遍历数组,如果找到文本,则将 marginBottom 设置为 accumulator * 5px 的值并将该文本包装到 <p> 中,然后将 accumulator 重置为 0。
  3. 如果发现空字符串,则将累加器加 1。

也许有更好的方法?

1 个答案:

答案 0 :(得分:0)

使用 js 设置样式也很棘手,因为您的方法会导致复杂的计算.. 留给 css 并使用 html 标签!

查看示例 =>

HTML

<div id="main"></div>

CSS

.spacer {
  display: block;
  height: 5px; /* Adjust the margin by changing height */
}

JS

const main = document.querySelector('#main')

let array = [
  'Hello world',
  '',
  '',
  'This is the first line',
  '',
  'This is the second line',
  '',
  '',
  '',
  '',
  'This is the last line'
]

let html = "";
array.forEach(val => val === "" ? html += "<div class='spacer'></div>": html += `<p> ${val} </p>`)

main.innerHTML = html;
相关问题