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
已添加,但没有多个空格。
如何保留原始的空格数?
答案 0 :(得分:1)
使用
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>
答案 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 ipsum</div>";
答案 2 :(得分:0)
使用HTML不间断空格
let a = "<div class='child'>lorem 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>