简体   繁体   中英

Javascript function to add margin to <p> tags depending on new lines

I have a text with new lines on javascript. I used text.split('\\n') to split it into an array.

So what I have now is this:

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

I want each new line to be 5px of margin, so I want to convert it to this:

<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>

I think I can write a function to do it like this:

  1. Start an accumulator in 0.
  2. Loop through the array, from the top down, if you find text, set the marginBottom with the value of accumulator * 5px and wrap that text into a <p> , then reset the accumulator to 0.
  3. If you find empty string, then add 1 to the accumulator.

Maybe there's a better way of doing it?

Using js to set styles can be tricky also by your method it would lead to complex calculations .. Leave to css and use html tags !

See example =>

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM