我在 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>
我想我可以写一个函数来做到这一点:
<p>
中,然后将 accumulator 重置为 0。也许有更好的方法?
答案 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;