追加时如何保留多个空格

时间:2018-10-26 07:53:36

标签: jquery append

let a = "<div class='child'>lorem       ipsum</div>";
$('#parent').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='parent'>
<div class='child'>lorem ipsum</div>
</div>

您可以看到a已添加,但没有多个空格。

如何保留原始的空格数?

4 个答案:

答案 0 :(得分:1)

使用&nbsp;

let a = "<div class='child'>lorem &nbsp;&nbsp;&nbsp;&nbsp;ipsum</div>";
$('#parent').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='parent'>
  <div class='child'>lorem ipsum</div>
</div>

答案 1 :(得分:0)

一种方法是将内容放入pre标记中,该标记的CSS设置为从其父项继承font样式:

let a = "<div class='child'><pre>lorem       ipsum</pre></div>";
$('#parent').append(a);
#parent pre {
  font: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='parent'>
<div class='child'>lorem ipsum</div>
</div>

或者,您可以在字符串中使用不间断空格:

let a = "<div class='child'>lorem&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ipsum</div>";

答案 2 :(得分:0)

使用HTML不间断空格&nbsp;

let a = "<div class='child'>lorem &nbsp;&nbsp;&nbsp; ipsum</div>";

答案 3 :(得分:0)

您还可以使用textarea元素a删除所有默认样式,如下所示:

let a = "<div class='child'><textarea>lorem       ipsum</textarea></div>";
$('#parent').append(a);
.child{
  cursor: text;
}
textarea{
  border: 0;
  pointer-events: none;
  border: none;
  overflow: auto;
  outline: none;
  box-shadow: none;
  resize: none;
  font-size: 16px;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='parent'>
<div class='child'>lorem ipsum</div>
</div>